I need to flatten nested object to an array of objects. So far this is what i came up with. But it is not working properly. Currently I'm checking the current element is object or not, if it is an object I'm calling same function recursively.
As the output i need this.
[
{title: 'Foo', value: 111},
{title: 'Bar', value: 222},
...
]
var data = {
1: {
title: "Foo",
value: 111,
children: {
2: {
title: "Bar",
value: 222,
},
},
},
3: {
title: "Baz",
value: 333,
children: {
4: {
title: "Qux",
value: 444,
children: {
5: {
title: "Quux",
value: 555,
},
},
},
},
},
};
const finalArrayOfObjects = [];
const flattenObject = (obj) => {
const flattened = {};
Object.keys(obj).forEach((key) => {
if (typeof obj[key] === "object" && obj[key] !== null) {
flattenObject(obj[key]);
} else {
flattened[key] = obj[key];
}
finalArrayOfObjects.push(flattened);
console.log(flattened);
});
};
-
stackoverflow.com/questions/30048388/… might be helpfulevolutionxbox– evolutionxbox2021年09月09日 15:18:22 +00:00Commented Sep 9, 2021 at 15:18
3 Answers 3
Here's one way, using a recursive generator function.
var data = {
1: {
title: "Foo",
value: 111,
children: {
2: {
title: "Bar",
value: 222,
},
},
},
3: {
title: "Baz",
value: 333,
children: {
4: {
title: "Qux",
value: 444,
children: {
5: {
title: "Quux",
value: 555,
},
},
},
},
},
};
function *forAllChildren(obj) {
for (let key in obj) {
let { children, ...objWithoutChildren} = obj[key];
yield objWithoutChildren;
yield *forAllChildren(obj[key].children);
}
}
const result = [...forAllChildren(data)]
console.log(result);
Comments
Hope this work for you
var finalArrayOfObjects = [];
var flattenObject = (obj) => {
for(var key in obj) {
// { title , value, children}
var data = obj[key]
if (data.children) {
// data.children = { key : {title , value, children} }
flattenObject(data.children)
}
finalArrayOfObjects.push({
title : data.title,
value : data.value,
})
}
}
flattenObject(data)
console.log(finalArrayOfObjects)
Comments
Time to once again prove the power of Functional Programming & Recursion
var data = {
1: {
title: "Foo",
value: 111,
children: {
2: {
title: "Bar",
value: 222,
},
},
},
3: {
title: "Baz",
value: 333,
children: {
4: {
title: "Qux",
value: 444,
children: {
5: {
title: "Quux",
value: 555,
},
},
},
},
},
};
const dictAsArray = Object.values(data);
const flat = [];
function drill(array) {
array.map(obj => {
recursiveCall(obj);
});
}
function recursiveCall(obj) {
if (obj.children) {
const children = JSON.parse(JSON.stringify(Object.values(obj.children)));
delete obj.children;
drill(children);
}
flat.push(obj);
}
dictAsArray.map(dict => recursiveCall(dict));
console.log(flat);
In this approach the children objects are removed from each object.
If you would like them to remain though, you can simply remove delete obj.children.