Convert Nested Json Object In Reactjs?
I've been playing with json objects & using ReactJS. One of the json object represented by variable 'res'. How do I convert 'res' into 'b'. I'm also getting my json object 're
Solution 1:
You could do something like the following:
const a = {
menu_1: {
id: "1",
menuitem: [{
value: "1",
onclick: "1()",
}, ],
},
menu_2: {
id: "2",
menuitem: [{
value: "2",
onclick: "2()",
}, ],
},
};
let b = Object.keys(a).reduce(
(p, c) => {
for (let item of a[c].menuitem) {
p.popup.menuitem.push(item);
}
return p;
}, {
popup: {
menuitem: []
}
}
);
console.log(b);
I'm assuming that object a
might have more than one menuitem
in the array.
Solution 2:
You can use reduce this way
const a = {
"menu_1": {
"id": "1",
"menuitem": [{
"value": "0",
"onclick": "0()"
}, {
"value": "0",
"onclick": "0()"
}]
},
"menu_2": {
"id": "2",
"menuitem": [{
"value": "2",
"onclick": "2()"
}]
}
}
const res = Object.values(a).reduce((all, {
menuitem
}) => {
all.popup.menuitem = [...all.popup.menuitem, ...menuitem]
return all
}, {
popup: {
menuitem: []
}
})
console.log(res)
Post a Comment for "Convert Nested Json Object In Reactjs?"