将具有相同值的对象推送到Array

时间:2017-09-14 03:57:21

标签: javascript

鉴于我们有对象数组:

let objects = [
  {name: 'bob'},
  {name: 'foo'},
  {name: 'bar'},
  {name: 'foo'},
  {name: 'foo'}
]

如何将此数组转换为此数组:

let objects = [
  [
    {name: 'bob'}
  ],
  [
    {name: 'foo'},
    {name: 'foo'},
    {name: 'foo'}
  ],
  [
    {name: 'bar'}
  ]
]

高阶函数

2 个答案:

答案 0 :(得分:2)

您可以使用array .reduce() method迭代数组并将每个对象放入一个关键字name属性的工作对象中的数组中,然后使用Object.values()转换该工作将对象转换为数组数组:

let objects = [
  {name: 'bob'},
  {name: 'foo'},
  {name: 'bar'},
  {name: 'foo'},
  {name: 'foo'}
]

let result = Object.values(objects.reduce((a,c) => {
  if (!a[c.name]) a[c.name] = []
  a[c.name].push(c)
  return a
}, {}))

console.log(result)

答案 1 :(得分:1)



let objects = [{
    name: 'bob'
  },
  {
    name: 'foo'
  },
  {
    name: 'bar'
  },
  {
    name: 'foo'
  },
  {
    name: 'foo'
  }
]
let result = objects.reduce((accumulator, currentValue) => {
  if (!Array.isArray(accumulator)) {
    //console.log("once")
    var temp = accumulator;
    accumulator = [
      [],
      [],
      []
    ];
    accumulator[0].push(temp)
    return accumulator;
  }
  
 

  for(var i = 0; i < accumulator.length;i++){
  //console.log(accumulator[i][0],currentValue.name)

    if(accumulator[i][0] == undefined){
    //console.log("was undefined")
      accumulator[i] =[currentValue]
      return accumulator;
    }else if(accumulator[i][0].name == currentValue.name){
      //console.log("found match")
      accumulator[i].push(currentValue)
      return accumulator;
    }  
  }



  return accumulator;
});

console.log(result)
&#13;
&#13;
&#13;