在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()"

          }

        ]

      }

    }


紫衣仙女
浏览 220回答 2
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。

Cats萌萌

您可以通过这种方式使用 reduceconst 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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript