如何从复杂的数组对象结构中获取数据?

时间:2018-10-26 15:58:09

标签: javascript reactjs

我有这样的东西

data: {
      dataFirst: { 
        Food: [ {id: 536131, name: "option1", }]
      },       
      dataSecond: { 
        Autos: [{id: 678, name: 'option1'}],
        Houses: [
          {id: 6876, name: "option1"},
          {id: 6876, name: "Placed App"},
        ],
        Phones: [
          {id: 672, name: "option1"},
          {id: 97249, name: "Placed},
        ],
        Food: [
          {id: 772, name: "option1"},
          {id: 6777, name: "Placed},
        ], 
      }
    }  

问题是,我在dataFirst和dataSecond中可能有相同的数据,例如“食物”,我有2个包含不同数据的数组对象,但是我需要使用来自2个数据的数据使它成为一个“食物”对象它们分别来自dataFirst“食物”和dataSecond“食物”。我有这样的代码:

export const parser = ({ data }) => {
  const result = Object.values(data).reduce((prev, topicsGroup) => {
    Object.assign(prev, topicsGroup);
    return prev;
  }, {});
  return result;
}

,但是此代码不会合并2个“食物”对象,而是仅从dataFirst个“食物”对象返回第二个食物对象。

1 个答案:

答案 0 :(得分:2)

您可以使用Object.values(data)遍历主数据对象的所有值,并通过串联对应于通用键的数组将它们与reduce组合:

let data = {
  dataFirst: {
    Food: [{
      id: 536131,
      name: "option1",
    }]
  },
  dataSecond: {
    Autos: [{
      topicId: 678,
      name: 'option1'
    }],
    Houses: [{
        topicId: 6876,
        name: "option1"
      },
      {
        topicId: 6876,
        topicName: "Placed App"
      },
    ],
    Phones: [{
        topicId: 672,
        name: "option1"
      },
      {
        topicId: 97249,
        name: "Placed"
      },
    ],
    Food: [{
        topicId: 772,
        name: "option1"
      },
      {
        topicId: 6777,
        name: "Placed"
      },
    ],
  }
};


let res = Object.values(data).reduce((acc, curr) => {
  Object.entries(curr).forEach(([k, v]) => {
    if (k in acc) acc[k] = acc[k].concat(v);
    else acc[k] = v;
  });
  return acc;
}, {});

console.log(res);