I have this data:
const data = [
{
"id": 1,
"subRows": [
{
"id": 1,
"subRows": [
{
"id": 1,
}
]
},
{
"id": 2,
"subRows": [
{
"id": 4,
}
]
},
]
},
{
"id": 55,
"subRows": []
}
];
and i need to get from this data like that, that will relay all the nesting of starter data:
const result = {
'0': false,
'0.0': false,
'0.0.0': false,
'0.1.0': false,
'0.1.1': false,
'1: false'
}
I need it in order to represent nesting in starting data and transform it to format, that react-table expended initial state is require. (https://react-table.tanstack.com/docs/api/useExpanded). I want to store it in local storage to prevent expanding state changing with page reload.
Take a recursive approach and ahnd over the last key as new prefix.
const
flat = (array, prefix = '') => array.reduce((r, o, i) => {
const key = prefix + (prefix && '.') + i;
return {
...r,
[key]: false,
...flat(o.subRows || [], key)
};
}, {});
data = [{ id: 1, subRows: [{ id: 1, subRows: [{ id: 1 }] }, { id: 2, subRows: [{ id: 4 }] }] }, { id: 55, subRows: [] }],
result = flat(data);
console.log(result);