我正在研究一个小型的React项目,但现在我陷入了困境。 我需要根据数组对象键进行分组。
下面是数组:
let addOnFeatures = [
{"name": "feature1", id: 101, cost: 100},
{"name": "feature2", id: 102, cost: 200},
{"name": "feature1", id: 103, cost: 300},
{"name": "feature3", id: 104, cost: 40}
]
我需要根据名称键进行分组,以便每个与通用名称相关的ID都应显示在其自己的标签上。
预期输出应为
*uniqueFeaturename
id: cost
示例:
1. feature1
101 : 100
103 : 300
2. feature2
102 : 200
3. feature3
104: 40
答案 0 :(得分:2)
只需使用Array.prototype.reduce
并向对象添加元素,如
let addOnFeatures = [
{"name": "feature1", id: 101, cost: 100},
{"name": "feature2", id: 102, cost: 200},
{"name": "feature1", id: 103, cost: 300},
{"name": "feature3", id: 104, cost: 40}
]
const res = addOnFeatures.reduce((acc, item) => {
if(acc[item.name]) {
acc[item.name] = {...acc[item.name], [item.id]: item.cost};
} else {
acc[item.name] = {[item.id]: item.cost};
}
return acc;
}, {});
console.log(res);
答案 1 :(得分:-1)
一个解决方案可以是:
let addOnFeatures = [
{"name": "feature1", id: 101, cost: 100},
{"name": "feature2", id: 102, cost: 200},
{"name": "feature1", id: 103, cost: 300},
{"name": "feature3", id: 104, cost: 40}
];
var res={};
addOnFeatures.forEach(i=>{
if(!res[i.name]){
res[i.name] = [{id: i.id, cost:i.cost}]
}else{
res[i.name].push({id: i.id, cost:i.cost})
}
}
);
console.log(res)
let addOnFeatures = [
{"name": "feature1", id: 101, cost: 100},
{"name": "feature2", id: 102, cost: 200},
{"name": "feature1", id: 103, cost: 300},
{"name": "feature3", id: 104, cost: 40}
];
var res2={};
addOnFeatures.forEach(i=>{
res2[i.name] = res2[i.name] ? [...res2[i.name],...[{id: i.id, cost:i.cost}]] :[...[{id: i.id, cost:i.cost}]]
}
);
console.log(res2)