假设我有一个由四个对象组成的数组
var data = [
{a: 1, b: 2},
{a: 2, b: 4},
{a: 1, b: 6},
{a: 2, b: 9}
];我想要创建一个对象,比如接受公共值并将其作为键传递,并将值ob公共对象分配给如下所示的数组
Const treat = {
1:[{a:1,b:2} {a:1,b:6}],
2:[{a:2,b:4} {a:2,b:9}]
}发布于 2022-07-29 17:42:34
这是你想要的一个版本。您可以研究不同的数组方法,如reduce,以查看获得类似结果的其他方法。
var data = [{
a: 1,
b: 2
},
{
a: 2,
b: 4
},
{
a: 1,
b: 6
},
{
a: 2,
b: 9
}
];
function sortData() {
var sortedData = {};
data.forEach(sample => {
// Need to check if the array for the sample has been created since we cannot "push" to "undefined".
if (sortedData[sample.a]) {
sortedData[sample.a].push(sample);
} else {
sortedData[sample.a] = [sample];
}
});
return sortedData;
}
console.log(sortData());
https://stackoverflow.com/questions/73169077
复制相似问题