How to split a multidimensional object?
-
there is a deep object of the kind
{ name: "one" children: [ { name: "two", children[{ name: "three", children[]}] }, { name: "four", children[{ name: "five", children[]}] } ] }
etc.
you need to get from this another object of the form
{ one: [{listOfChildren}], two: [{listOfChildren}] three:[{listOfChildren}] }
If there are no children, then do not create key: valueJavaScript Adalaide Bates, Apr 9, 2019 -
If, of course, you understood correctly.
const collect = (entries, store = {}) => {
for (const entry of entries) {
const { name, ...data } = entry;
if (data.children.length > 0) {
store[name] = data;
collect(data.children, store);
}
}
return store;
};Sebastian Carr -
What are the problems?
If you want - recursively:function toFlatMap(array, map = {}) {
for(const {name, children} of array) {
map[name] = children;
toFlatMap(children, map);
}
return map;
}
Do you want - linearly:function toFlatMap(array, map = {}) {
let stack = array.slice();
let current;
while(current = stack.shift()) {
map[current.name] = current.children;
stack.push(...current.children);
}
return map;
}Fynn Garcia -
Thank you all, I found the solution myself)
Most of all, the solution is Alexander
let menu = {}
function getMenu(obj){
if(obj.children.length > 0){
menu[obj.url] = obj.children
}
obj.children.map(i => getMenu(i))
return menu;
}Alexander Weaver
3 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!