问题
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 'res' from an api.
I've reciprocated my problem over this link: https://codesandbox.io/s/epic-leaf-sznhx?file=/src/App.js
const [res, setResult] = useState();
useEffect(() => {
(async () => {
axios.get("https://corona.lmao.ninja/v2/countries").then(response => {
setResult(response.data);
});
})();
}, []);
How do I convert this:
const a =
{
"menu_1": {
"id": "1",
"menuitem": [{
"value": "0",
"onclick": "0()"
}, {
"value": "0",
"onclick": "0()"
}]
},
"menu_2": {
"id": "2",
"menuitem": [{
"value": "2",
"onclick": "2()"
}]
}
}
into this json object:
const b =
{
"popup": {
"menuitem": [
{
"value": "0",
"onclick": "0()"
},
{
"value": "0",
"onclick": "0()"
},
{
"value": "2",
"onclick": "2()"
}
]
}
}
回答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.
回答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)
来源:https://stackoverflow.com/questions/61313553/convert-nested-json-object-in-reactjs