I have a nested object structure and I perform a serie of operations on each object and then I push it to an array. My current code looks like this:
var item;
var final_data = [];
function walk (items, level) {
for (var i = 0; i < items.length; i++) {
item = items[i];
var final_item = Object.assign({}, item); // <-- required step, object's proper key/values must be cloned, but not recursively.
delete final_item.children; // final_item shouldn't have children
final_item.foo = level;
final_data.push(final_item);
if ("children" in item) walk(item.children, level + 1);
}
}
walk(my_data, 0);
My current code works as expected, as in, it flattens the input data.
My question is if there is a way to improve that code (performance wise).
Edit:
my_data
is an array of nested objects, like this:
my_data = [
{a: 1, b: 2},
{a: 3, b: 8},
{a: 9, b: 3, children: [
{...}, {...}, {...}
]},
{...},
{..., children: [{}, {}, {}...]}
];