使用lodash将数组合并到对象

时间:2018-12-06 03:25:33

标签: javascript lodash

我正在尝试操纵此示例对象数组。

var data = [
  { id: 'A1', name: 'Test', gender: 0, pet: 'dog', petname: 'huahua' },
  { id: 'A1', name: 'Test', gender: 0, pet: 'cat', petname: 'meo' },
  { id: 'A1', name: 'Test', gender: 0, pet: 'snake', petname: 'snakke' },
  { id: 'A1', name: 'Test', gender: 0, pet: 'lion', petname: 'growww' },
];

我需要做的就是将数组合并到一个这样的对象

var data = [
  {
    id: 'A1', name: 'Test', gender: 0, pet: [
      { type: 'dog', petname: 'huahua' },
      { type: 'cat', petname: 'meo' },
      { type: 'snake', petname: 'snakke' },
      { type: 'lion', petname: 'growww' },
    ]
  },
];

使用lodash最简单的方法是什么?请帮助我。

2 个答案:

答案 0 :(得分:0)

不需要任何库,只需使用reduce即可。

var data= [
  { id: 'A1', name: 'Test', gender: 0, pet: 'dog', petname: 'huahua'},
  { id: 'A1', name: 'Test', gender: 0, pet: 'cat', petname: 'meo'},
  { id: 'A1', name: 'Test', gender: 0, pet: 'snake', petname: 'snakke'},
  { id: 'A1', name: 'Test', gender: 0, pet: 'lion', petname: 'growww'}
];

const results = data.reduce((results, current) => {
  const owner = results.find(o => o.id === current.id);
  if (owner) {
    owner.pet.push({ type: current.pet, petname: current.petname });
  } else {
    results.push({id: current.id, name: current.name, gender: current.gender, pet: [{ type: current.pet, petname: current.petname }]});
  }
  return results;
}, []);

console.log(results);

答案 1 :(得分:0)

您可以通过Array.reduce和ES6 destructuring以简洁的方式执行此操作:

var data= [ { id: 'A1', name: 'Test', gender: 0, pet: 'dog', petname: 'huahua'}, { id: 'A1', name: 'Test', gender: 0, pet: 'cat', petname: 'meo'}, { id: 'A1', name: 'Test', gender: 0, pet: 'snake', petname: 'snakke'}, { id: 'A1', name: 'Test', gender: 0, pet: 'lion', petname: 'growww'}, ];

const result = data.reduce((r, {id, name, gender, pet, petname}, i, a) => {
  r.pet.push({ type: pet, petname})
  return i == a.length-1 ? {id, name, gender, pet: r.pet} : r
}, { pet: []})

console.log(result)