使用ES6根据属性将javascript对象数组转换为数组的键-值对

时间:2018-10-26 10:50:26

标签: javascript arrays typescript object

可以说我有以下对象数组:

myArray = [
  {name: 'First', parent: 1, delta: 2},
  {name: 'Second', parent: 1, delta: 1},
  {name: 'Third', parent: 2, delta: 1}
];

我想将此数组转换为具有父项键和对象值的对象。例如:

result = {
  1: [
       {name: 'First', parent: 1, delta: 2},
       {name: 'Second', parent: 1, delta: 1}
     ],
  2: [
       {name: 'Third', parent: 2, delta: 1}
     ]
}

我可以使用forEach或嵌套循环来执行此操作,但是我想知道是否有一种使用ES6语法的方法可以使它更简洁/内联,这将使我能够进行诸如sort on delta

4 个答案:

答案 0 :(得分:2)

您可以使用Array.reduce()

let myArray = [{
    name: 'First',
    parent: 1,
    delta: 2
  },
  {
    name: 'Second',
    parent: 1,
    delta: 1
  },
  {
    name: 'Third',
    parent: 2,
    delta: 1
  }
];
var res = myArray.reduce((acc, item) => {
  if (acc[item.parent]) {
    acc[item.parent].push(item);
  } else {
    acc[item.parent] = [item];
  }
  return acc;
}, {});
console.log(res);

答案 1 :(得分:1)

您可以使用reduce实现这一目标

var myArray = [
  {name: 'First', parent: 1, delta: 2},
  {name: 'Second', parent: 1, delta: 1},
  {name: 'Third', parent: 2, delta: 1}
];

var result = myArray.reduce((o,d) =>
             (
               o[d.parent] = (o[d.parent] || []).concat(d)
               , o
             )
             , {})
console.log(result)

答案 2 :(得分:1)

var myArray = [
  {name: 'First', parent: 1, delta: 2},
  {name: 'Second', parent: 1, delta: 1},
  {name: 'Third', parent: 2, delta: 1}
];

console.log(myArray.reduce((acc, val)=>({...acc, [val.parent]: (acc[val.parent] || []).concat(val)}), {}))

答案 3 :(得分:1)

const result = myArray.reduce((result, el) => {
  if (result[el.parent]) result[el.parent].push(el);
  else result[el.parent] = [el];
  return result;
}, {});