将值作为索引数组的对象分组

时间:2017-04-19 09:35:00

标签: javascript arrays object lodash

我的输出格式为

[{"name":"ABC",
"type":123
},
{"name":"ABC",
"type":111
},
{"name":"ABC",
"type":1432
},
{"name":"XYZ",
    "type":523
},
{"name":"XYZ",
    "type":52
}];

我正在尝试创建一个索引位置为数组

的分组对象

示例输出:

{
"ABC":[0,1,2],
"XYZ":[3,4]
}

3 个答案:

答案 0 :(得分:4)

可以使用Array#reduce()

完成此操作

var array = [{
    "name": "ABC",
    "type": 123
  },
  {
    "name": "ABC",
    "type": 111
  },
  {
    "name": "ABC",
    "type": 1432
  },
  {
    "name": "XYZ",
    "type": 523
  },
  {
    "name": "XYZ",
    "type": 52
  }
];

var groups = array.reduce((o,a,i)=>{
  o[a.name]=o[a.name]||[];
  o[a.name].push(i);
  return o;
}, {});

console.log(groups);
.as-console-wrapper { max-height: 100% !important; top: 0; }

在单行中你会有

var groups = array.reduce((o,a,i)=>(o[a.name]=o[a.name]||[],o[a.name].push(i),o),{});

答案 1 :(得分:2)

您可以按name对其进行分组并推送索引。



var array = [{ name: "ABC", type: 123 }, { name: "ABC", type: 111 }, { name: "ABC", type: 1432 }, { name: "XYZ", type: 523 }, { name: "XYZ", type: 52 }], 
    result = array.reduce(function (r, a, i) {
        (r[a.name] = r[a.name] || []).push(i);
        return r;
    }, Object.create(null));
    
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 2 :(得分:0)

你走了:

var newObj=[];
var digitArray=[];
var myObj=[{"name":"ABC",
"type":123
},
{"name":"ABC",
"type":111
},
{"name":"ABC",
"type":1432
},
{"name":"XYZ",
"type":523
},
{"name":"XYZ",
"type":52
}];
for (var i=0; i<=myObj.length-1; i++){
    digitArray = (""+myObj[i].type).split("");
    newObj[myObj[i].name]=digitArray;
}
console.log(newObj);

https://jsfiddle.net/9jd9rdgg/