为了账号安全,请及时绑定邮箱和手机立即绑定

使用javascript从上到下获取json数据

使用javascript从上到下获取json数据

小唯快跑啊 2024-01-18 16:59:02
我正在尝试从上到下获取 json 数据
查看完整描述

3 回答

?
一只甜甜圈

TA贡献1836条经验 获得超5个赞

尝试这个:


    const finalResult = {};

    const data = {

        "data": [

          {

            "persons": {

              "Dupont nicolas": "President",

              "George frimaolo": "engineer",

              "Tiprana masilo": "football player"

            }

          },

          {

            "persons": {

              "Balack martini": "author",

              "Dupont nicolas": "Student",

              "Joseph Allen": "dentist"

            }

          },

          {

            "persons": {

              "Fred Samanta": "baker",

              "Romero flagipi": "actor",

              "Fred Samanta": "astronaut",

              "Joseph Allen": "pilot",

              "Anne Hedley": "teacher"

            }

          }

        ]

      }

    

    for (let i in data.data) {

      for (let j in data.data[i].persons) {

        finalResult[j] = finalResult[j] ? finalResult[j] : data.data[i].persons[j];

      }

    }

    

    console.log(finalResult);


查看完整回答
反对 回复 2024-01-18
?
不负相思意

TA贡献1777条经验 获得超10个赞

使用reduce和Object.assign


const combine = (arr) =>

  arr.reduce((acc, { persons }) => Object.assign(acc, persons), {});


const data = [

  {

    persons: {

      "Dupont nicolas": "President",

      "George frimaolo": "engineer",

      "Tiprana masilo": "football player",

    },

  },

  {

    persons: {

      "Balack martini": "author",

      "Dupont nicolas": "Student",

      "Joseph Allen": "dentist",

    },

  },

  {

    persons: {

      "Fred Samanta": "baker",

      "Romero flagipi": "actor",

      "Fred Samanta": "astronaut",

      "Joseph Allen": "pilot",

      "Anne Hedley": "teacher",

    },

  },

];


console.log(combine(data))


查看完整回答
反对 回复 2024-01-18
?
芜湖不芜

TA贡献1796条经验 获得超7个赞

一个简单的Array.reduce应该可以实现你的目标。


const obj = {

  // json data shown in your question

}


const result = obj.data.reduce(

  (acc, cur) => ({

    ...cur.persons,

    ...acc,

  }),

  {}

);



查看完整回答
反对 回复 2024-01-18
  • 3 回答
  • 0 关注
  • 46 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信