我有这种类型的对象
students = [
{
"name": "Ana Barbique",
"category":"B"
}
{
"name": "Marko Polo",
"category":"B"
}
{
"name": "Nick Harper",
"category":"A"
}
]
我希望它拥有这种类型的对象数组:
sum = [
{
"category": "A",
"count" : 1
}
{
"category": "B",
"count" : 2
}
]
所以基本上我想让对象数组具有出现在学生中的类别及其数量。订单无关紧要。我以前没有这样做过。
答案 0 :(得分:1)
首先通过减少students
数组
const categories = students
.reduce((cat, student) => (
cat[student.category]++ || (cat[student.category] = 1), cat
), {})
然后迭代类别'用于创建所需数组的键
const sum = Object
.keys(categories)
.map(name => ({category: name, count: categories[name]}))
答案 1 :(得分:0)
这是一个纯粹的循环&查找方法。 Yuri Tarabanko的答案很简单。
这种方法的关键是使用check数组对象来保存sum []数组中每个类别的索引。这是一种有用的技术。
var students = [
{
"name": "Ana Barbique",
"category":"B"
},
{
"name": "Marko Polo",
"category":"B"
},
{
"name": "Nick Harper",
"category":"A"
}
]
var sum = [], check = [], obj;
for (var i = 0; i < students.length; i = i + 1) {
obj = students[i];
if ( check[obj.category] !== undefined ) {
// object has already been seen so add to sum array count
sum[check[obj.category]].count = sum[check[obj.category]].count + 1;
}
else {
// object has not been seen so insert new.
sum.push({"category": obj.category, "count": 1});
check[obj.category] = sum.length - 1; // note index of category in sum array.
}
}
console.log('sum = ' + JSON.stringify(sum));