Convert nested json object in reactJS?

时光总嘲笑我的痴心妄想 提交于 2020-05-30 07:55:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!