我有对象数组,但我想创建它的数组: 对象格式为:
[
{"name":"A1","type":"type1"},
{"name":"A2","type":"type1"},
{"name":"A3","type":"type1"},
{"name":"A4","type":"type1"},
{"name":"B1","type":"type2"},
{"name":"C1","type":"type3"},
{"name":"D1","type":"type4"},
{"name":"D2","type":"type4"}
结果格式为:
["type1"=>[A1,A2,A3,A4],"type2"=>[B1],"type3"=>[C1],"type3"=>[D1,D2]]
答案 0 :(得分:0)
您可以使用Array#forEach
迭代数组,并使用类型为键的对象。
var data = [{ "name": "A1", "type": "type1" }, { "name": "A2", "type": "type1" }, { "name": "A3", "type": "type1" }, { "name": "A4", "type": "type1" }, { "name": "B1", "type": "type2" }, { "name": "C1", "type": "type3" }, { "name": "D1", "type": "type4" }, { "name": "D2", "type": "type4" }],
grouped = {};
data.forEach(function (a) {
grouped[a.type] = grouped[a.type] || [];
grouped[a.type].push(a.name);
});
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)