我正在为自己的组件之一创建数据集, 当前数据是
[
{name : "John" , id : "123"} ,
{name : "Josh" , id : "1234"},
{name : "Charlie" , id : "1234253"},
{name : "Charles" , id : "123345"}
]
想像这样分组
{
C : [{name:"Charlie",id:"1234253"},{name:"Charles",id:"123345"}],
J : [{name:"John",id:"123"},{name:"Josh",id:"1234"}]
}
答案 0 :(得分:2)
您可以像这样使用reduce
var data = [
{name : "John" , id : "123"} ,
{name : "Josh" , id : "1234"},
{name : "Charlie" , id : "1234253"},
{name : "Charles" , id : "123345"}
];
let result = data.reduce((r, e) => {
let group = e.name[0];
if(!r[group]) r[group] = [e]
else r[group].push(e);
return r;
}, {})
console.log(result);
答案 1 :(得分:0)
您要检查输入数组中的所有对象,然后将其推入由对象名称的首字母标识的数组。
var input = [{
name: "John",
id: "123"
},
{
name: "Josh",
id: "1234"
},
{
name: "Charlie",
id: "1234253"
},
{
name: "Charles",
id: "123345"
}
];
var result = {};
input.forEach(x => !!result[x.name[0]] ? result[x.name[0]].push(x) : result[x.name[0]] = [x]);
console.log(result);