javascript - 在reactJS中转换嵌套的json对象?
问题描述
我一直在玩 json 对象和使用 ReactJS。由变量“res”表示的 json 对象之一。如何将“res”转换为“b”。我还从 api 获取我的 json 对象“res”。
我已经通过此链接解决了我的问题: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);
});
})();
}, []);
我如何转换这个:
const a =
{
"menu_1": {
"id": "1",
"menuitem": [{
"value": "0",
"onclick": "0()"
}, {
"value": "0",
"onclick": "0()"
}]
},
"menu_2": {
"id": "2",
"menuitem": [{
"value": "2",
"onclick": "2()"
}]
}
}
进入这个 json 对象:
const b =
{
"popup": {
"menuitem": [
{
"value": "0",
"onclick": "0()"
},
{
"value": "0",
"onclick": "0()"
},
{
"value": "2",
"onclick": "2()"
}
]
}
}
解决方案
您可以执行以下操作:
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);
我假设该对象在数组中a
可能有多个menuitem
。
推荐阅读
- python-3.x - 如何修复 lambda 行以使我的 if 工作?
- sms - 如何在 Twilio SMS webhook URL 中传递 from 和 body 作为参数
- arduino - Arduino esp8266 限制 IP 地址
- selenium - 使用 Protractor 使用 browserstack 上传本地文件
- python - 使用 PyInstaller 将 .py 转换为 .exe 时,如何解决缺少模块的问题?
- centos - 在 Centos 6.9 上安装 Ansible
- laravel - PHPUnit 因进程隔离而失败,但在没有该标志的情况下通过
- jquery - 从 Google 电子表格中提取后,如果单元格为空,则隐藏表格
- java - Jersey JAX-RS 依赖注入
- php - 如何使用此 PHP 登录设置修复 too_many_redirects