繁体   English   中英

JS(ES6):根据对象属性简化数组

[英]JS (ES6): Reduce array based on object attribute

我有一个像这样的数组:

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 }
];

现在,我想简化此数组,以查看每年有多少个水果,总数是多少。 这样结果看起来像这样:

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的助手?

使用Object.valuesreduce

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); 

您可以使用array#reduce根据年份对数据进行分组,并在对象累加器中计算水果的出现次数。 然后使用Object.values()从该对象获取所有值

 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 } ], result = Object.values(fruits.reduce((r,{fruit, year}) => { r[year] = r[year] || {year}; r[year][fruit] = (r[year][fruit] || 0) + 1; r[year]['total'] = (r[year]['total'] || 0) + 1; return r; },{})); console.log(result); 

您可以使用数组作为结果集,以保持年份的给定顺序。

 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 }], result = fruits.reduce((r, { year, fruit }) => { var item = r.find(o => o.year === year); if (!item) { r.push(item = { year }); } item[fruit] = (item[fruit] || 0) + 1; return r; }, []); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM