5 回答
TA贡献1810条经验 获得超5个赞
这是适合您的解决方案:
let cars = [
{ id: 1, name: "Mercedes", year: "2015" },
{ id: 2, name: "Mercedes", year: "2000" },
{ id: 3, name: "BMW", year: "2010" },
{ id: 4, name: "BMW", year: "2004" },
{ id: 5, name: "Volvo", year: "2012" },
{ id: 6, name: "Volvo", year: "2014" },
];
let numbers = cars.reduce((acc, child) => {
if (!acc[child.name]) {
acc[child.name] = 0;
}
acc[child.name]++;
return acc;
}, {});
console.log(numbers);
TA贡献1829条经验 获得超7个赞
let cars = [
{ id: 1, name: "Mercedes", year: "2015" },
{ id: 2, name: "Mercedes", year: "2000" },
{ id: 3, name: "BMW", year: "2010" },
{ id: 4, name: "BMW", year: "2004" },
{ id: 5, name: "Volvo", year: "2012" },
{ id: 6, name: "Volvo", year: "2014" },
{ id: 7, name: "Volvo", year: "2012" },
{ id: 8, name: "Volvo", year: "2014" },
{ id: 9, name: "Volvo", year: "2012" }
];
let result = cars.reduce((acc, child, index) => {
const indexFinded = acc.findIndex(el => el.name==child.name && el.year ==child.year);
const result = {}
if(indexFinded == -1) {
result.name = child.name;
result.year = child.year;
result.qtd = 1;
acc.push(result)
} else {
acc[indexFinded].qtd += 1
}
return acc;
}, []);
console.log(result);
TA贡献1906条经验 获得超3个赞
let cars = [
{id: 1, name: 'Mercedes', year: '2015'},
{id: 2, name: 'Mercedes', year: '2000'},
{id: 3, name: 'BMW', year: '2010'},
{id: 4, name: 'BMW', year: '2004'},
{id: 5, name: 'Volvo', year: '2012'},
{id: 6, name: 'Volvo', year: '2014'}
];
let obj = {}
cars.forEach((item) => {
//console.log(obj[item.name]) this return as undefined
if (!obj[item.name]) {
obj[item.name] = 1;
} else {
obj[item.name] += 1;
}
})
console.log(obj)
TA贡献1802条经验 获得超6个赞
您可以使用一个简单的reduce函数,该函数将遍历每个对象并将计数加一
let cars = [
{ id: 1, name: "Mercedes", year: "2015" },
{ id: 2, name: "Mercedes", year: "2000" },
{ id: 3, name: "BMW", year: "2010" },
{ id: 4, name: "BMW", year: "2004" },
{ id: 5, name: "Volvo", year: "2012" },
{ id: 6, name: "Volvo", year: "2014" }
];
let count = cars.reduce((acc, child) => {
acc[child.name] = (acc[child.name] || 0) + 1;
return acc;
}, {});
console.log(count);
TA贡献1820条经验 获得超2个赞
let counterObj = {}
let cars = [
{id: 1, name: 'Mercedes', year: '2015'},
{id: 2, name: 'Mercedes', year: '2000'},
{id: 3, name: 'BMW', year: '2010'},
{id: 4, name: 'BMW', year: '2004'},
{id: 5, name: 'Volvo', year: '2012'},
{id: 6, name: 'Volvo', year: '2014'}
];
for (property of cars){
counterObj[property.name] = 1 + (counterObj[property.name] || 0)
}
console.log(counterObj)
添加回答
举报