数组与对象转换

时间:2015-12-18 08:11:12

标签: javascript arrays

我有一个像这样的对象的数组:

arr = [
  {name: 'Igor', id: 1,....},
  {name: 'Anton', id: 1,.... },
  {name: 'Igor', id: 2,.... },
  {name: 'Peter', id: 2,.... },
  {name: 'Igor', id: 2,.... }
]

我需要获得新的数组:

arrId = [
  { id: 1, names: 'Igor, Anton' },
  { id: 2, names: 'Igor, Peter' }
]

无法想到好的解决方案

3 个答案:

答案 0 :(得分:4)

在此示例中,我使用mapreduce

function rearrange(arr) {

  // use `reduce` to build an object using the ids as keys
  // this allows us to place all the names with the same id together
  // note we pass in an empty object to act as our initial p argument.
  var out = arr.reduce(function (p, c) {
    var key = c.id, name = c.name;

    // if the key doesn't exist create it and set its value
    // to an empty array
    p[key] = p[key] || [];

    // add the name to the array if it doesn't already exist
    if (p[key].indexOf(name) === -1) p[key].push(name);
    return p;
  }, {});

  // use `map` to return an array of objects
  return Object.keys(out).map(function (el) {

    // make sure we use an integer for the id, and
    // join the array to get the appropriate output
    return { id: +el, names: out[el].join(', ') };
  });

}

rearrange(arr);

DEMO

输出

[
  {
    "id": 1,
    "names": "Igor, Anton"
  },
  {
    "id": 2,
    "names": "Igor, Peter"
  }
]

答案 1 :(得分:1)

您可以使用 reduce 功能

arr = [
  {name: 'Igor', id: 1},
  {name: 'Anton', id: 1 },
  {name: 'Igor', id: 2 },
  {name: 'Peter', id: 2 },
  {name: 'Igor', id: 2 }
]

//first group needed fields from items by id
var result = arr.reduce(function(acc,cur){
  if(!acc.map[cur.id]) {
    acc.map[cur.id] = {id:cur.id, names:{}};
    acc.result.push(acc.map[cur.id]);
    }
  acc.map[cur.id].names[cur.name]=true;
  return acc;
},{map:{},result:[]})
//do addtional transfrom from map object with names, to string separated by comma
.result.map(function(el){
  return {id:el.id, names: Object.keys(el.names).join(', ')};
});
console.log(result);
document.body.innerHTML = JSON.stringify(result,null, 2);

答案 2 :(得分:0)

var arrId = [];
var arrKey = {};
for( var counter = 0; counter < arr.length; counter++)
{ 
  var arrObj = arr[ counter ];
  if ( !arrKey[  arrObj[ "id" ] ] )
  {
    arrKey[  arrObj[ "id" ] ] = [];
  }
  arrKey[  arrObj[ "id" ] ].push( arrObj[ "name" ] );
}
for ( var id in arrKey )
{
  arrId.push( [ "id": id, names : arrKey[ id ].join( "," ) ] );
}
console.log(arrId );