如何将对象数组操作为不同的键和值? [英] How to manipulate an array of object into a different key and value?
本文介绍了如何将对象数组操作为不同的键和值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有这个数组:
[{date: "5/7/2021", name: "bob"},
{date: "5/6/2021", name: "bob"},
{date: "5/6/2021", name: "bob"},
{date: "5/6/2021", name: "bob"},]
如何把数组变成:
[ {"5/6/2021" : 3}, // 3 because there are 3 data with 5/6/2021 date
{"5/7/2021" : 1}] // 1 because there are 1 data with 5/7/2021 date
我的进步.updatedSales 是数组名称(编辑)
My Progress. updatedSales is the array name (Edit)
const temp = updatedSales.reduce((acc, { name, date }) => {
acc[name] = acc[name] || { name, dates: new Set(), totalSubmit: 0 };
acc[name].totalSubmit++;
acc[name].dates.add(date);
return acc;
}, {});
const result = Object.values(temp).map(({ name, dates, totalSubmit }) => ({ name, uniqueDate: dates.size, totalSubmit }));
const updatedSales=[{date: "5/7/2021", name: "bob"},
{date: "5/6/2021", name: "bob"},
{date: "5/6/2021", name: "bob"},
{date: "5/6/2021", name: "bob"},]
const temp = updatedSales.reduce((acc, { name, date }) => {
acc[name] = acc[name] || { name, dates: new Set(), totalSubmit: 0 };
acc[name].totalSubmit++;
acc[name].dates.add(date);
return acc;
}, {});
const result = Object.values(temp).map(({ name, dates, totalSubmit }) => ({ name, uniqueDate: dates.size, totalSubmit }));
console.log(result)
预期:
[ {"5/6/2021" : 3}, // 3 because there are 3 data with 5/6/2021 date
{"5/7/2021" : 1}]
现在:
[{name: "bob", uniqueDate: 3, totalSubmit: 36},
{name: "steve", uniqueDate: 12, totalSubmit: 116}]
我想要的输出是不同的日期,而不是名称.所以它就像5/6/2021"而不是鲍勃".
My desired output is the date to be different, not name. So its like "5/6/2021" instead of "bob".
推荐答案
只需对您的脚本稍加改动,您就会得到:
With just a few touches to your script you will get this:
const updatedSales=[{date: "5/7/2021", name: "bob"},
{date: "5/6/2021", name: "bob"},
{date: "5/6/2021", name: "bob"},
{date: "5/6/2021", name: "bob"},]
const temp = updatedSales.reduce((acc, { name, date }) => {
acc[date] = acc[date] || { date, dates: new Set(), totalSubmit: 0 };
acc[date].totalSubmit++;
acc[date].dates.add(date);
return acc;
}, {});
const result = Object.values(temp).map(({ date, dates, totalSubmit }) => ( {[date]: totalSubmit }) );
console.log(result)
或者,如果您真的愿意,可以将其缩减为单行":
Or, if you really want to, you can reduce it down to a "one-liner":
const result = Object.entries(
updatedSales.reduce((a,{date}) => {
a[date] = (a[date] || 0) + 1;
return a;
}, {}) ).map(([k,v])=> ( {[k]:v }) );
new Set()
在这里并不是真正需要的.
The new Set()
is not really required here.
这篇关于如何将对象数组操作为不同的键和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文