js - 数组中的数组

时间:2017-03-22 11:30:46

标签: javascript group-by

我有这个JS数组 -

var temp1 = [{name: 'john', ids: [2,4,5]},
{name: 'james', ids: [2]},
{name: 'adam', ids: [5,2]}]

我希望将它分组到 -

{
    2: [{name: 'john'}, {name: 'james'}, {name: 'adam'}],
    4: [{name: 'john'}],
    5: [{name: 'john'},{name: 'adam'}]
}

有人可以帮我吗?

4 个答案:

答案 0 :(得分:4)

var input = [{name: 'john', ids: [2,4,5]},
{name: 'james', ids: [2]},
{name: 'adam', ids: [5,2]}]

var output = input.reduce(function(a,c) {
  return c.ids.reduce(function(a,v) {
    (a[v] || (a[v] = [])).push({name: c.name})
    return a
  }, a)
}, {})

console.log(output)

答案 1 :(得分:0)

var x = [{name: 'john', ids: [2,4,5]},
{name: 'james', ids: [2]},
{name: 'adam', ids: [5,2]}];

var newObj = {};
for(i=0;i<x.length;i++) {
  for(j=0;j<x[i].ids.length;j++) {
    newObj[x[i].ids[j]] = newObj[x[i].ids[j]] || [];
    newObj[x[i].ids[j]].push({'name': x[i].name});
  }
}

console.log(newObj);

试试这个

答案 2 :(得分:0)

var arr = [{name: 'john', ids: [2,4,5]},{name: 'james', ids: [2]},{name: 'adam', ids: [5,2]}],
    obj = {};
    arr.forEach(function(v){
      v.ids.forEach(function(c){
        if (!obj[c]) {
          var arr = [];
          arr.push({name: v.name});
          obj[c] = arr;
        } else {
          obj[c].push({name: v.name});
        }
      })
    });
    
    console.log(obj);

答案 3 :(得分:0)

使用Array的高阶函数reduce。

function convertArr(arr) {
  if(arr !== undefined && arr.length) {
    var i = 0;
    var newObj = arr.reduce(function(obj, item){
      var ids = item.ids;
      var id;
      for(i = 0; i < ids.length; i++) {
        id = ids[i];
        if(obj[id] === undefined) {
          obj[id] = [];
          obj[id].push({name: item.name});
        } else {
          obj[id].push({name: item.name});
        }
      }
      return obj;
    }, {});
 }
 console.log(JSON.stringify(newObj));
 alert(JSON.stringify(newObj));
}
var temp1 = [{name: 'john', ids: [2,4,5]},
 {name: 'james', ids: [2]},
 {name: 'adam', ids: [5,2]}];

convertArr(temp1);

function convertArr(arr) {
	  if(arr !== undefined && arr.length) {
  	    var i = 0;
        var newObj = arr.reduce(function(obj, item){
          var ids = item.ids;
          var id;
          for(i = 0; i < ids.length; i++) {
            id = ids[i];
            if(obj[id] === undefined) {
        	  obj[id] = [];
              obj[id].push({name: item.name});
            } else {
        	  obj[id].push({name: item.name});
            }
          }
          return obj;
        }, {});
     }
     console.log(JSON.stringify(newObj));
     alert(JSON.stringify(newObj));
    }
    var temp1 = [{name: 'john', ids: [2,4,5]},
     {name: 'james', ids: [2]},
     {name: 'adam', ids: [5,2]}];

    convertArr(temp1);