JS(ES6):根据对象属性简化数组 [英] JS (ES6): Reduce array based on object attribute
本文介绍了JS(ES6):根据对象属性简化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的数组:
I have an array like this:
const fruits = [
{ fruit: 'apple', year: 2018 },
{ fruit: 'apple', year: 2018 },
{ fruit: 'banana', year: 2018 },
{ fruit: 'orange', year: 2018 },
{ fruit: 'apple', year: 2017 },
{ fruit: 'apple', year: 2016 }
];
现在,我想简化此数组,以查看每年有多少个水果以及总数.这样结果看起来像这样:
Now I want to reduce this array to see how many fruits there are each year and how much the total is. So that the result looks like this:
const result = [
{ year: 2018, apple: 2, banana: 1, orange: 1 total: 4 },
{ year: 2017, apple: 1, total: 1 },
{ year: 2016, apple: 1, total: 1 }
];
我尝试使用reduce,但是我不知道如何根据年份对它进行分组.也许还有lodash的助手?
I have tried with reduce, but I couldn't figure out how to group it based on the year. Maybe there is also a lodash helper?
推荐答案
使用Object.values
和reduce
var output = Object.values(fruits.reduce( (a,c) => {
a[c.year] = a[c.year] || { year : c.year };
a[c.year]["total"] = (a[c.year]["total"] || 0) + 1;
a[c.year][c.fruit] = (a[c.year][c.fruit] || 0) + 1;
return a;
},{}));
演示
var fruits = [{
fruit: 'apple',
year: 2018
},
{
fruit: 'apple',
year: 2018
},
{
fruit: 'banana',
year: 2018
},
{
fruit: 'orange',
year: 2018
},
{
fruit: 'apple',
year: 2017
},
{
fruit: 'apple',
year: 2016
}
];
var output = Object.values(fruits.reduce((a, c) => {
a[c.year] = a[c.year] || {
year: c.year
};
a[c.year]["total"] = (a[c.year]["total"] || 0) + 1;
a[c.year][c.fruit] = (a[c.year][c.fruit] || 0) + 1;
return a;
}, {}));
console.log(output);
这篇关于JS(ES6):根据对象属性简化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文