Javascript-计算对象数组中的重复项并将计数存储为新对象 [英] Javascript - Counting duplicates in object array and storing the count as a new object
问题描述
我有一系列的javascript对象是产品.这些产品以购物车的形式显示在列表中.
I have an array of javascript objects that are products. These products are displayed in a list as a cart.
我想根据_.id
值计算数组中重复产品的数量,并从数组中删除这些对象,并使用更新的版本和名为count
的新键(总值)来依赖它们此对象出现的次数.
I want to count the number of duplicate products in the array based in the _.id
value and remove these objects from the array and relace them with an updated version and a new key called count
with a value of the total number of times this object comes up.
到目前为止,我已经尝试了许多方法,并且在整个google上进行了搜索,但没有发现可以正确完成此工作的任何内容.
So far, I have tried numerous methods and I've searched all over google but there's nothing that I've found that can do the job correctly.
我将使用的数组类型的示例如下:
An example of the type of array that I will be using would be this:
[
{ _id: "5971df93bfef201237985c4d",
slug: "5971df93bfef201237985c4d",
taxPercentage: 23,
totalCost: 9.99,
currency: "EUR",
},
]
所以我希望我的最终结果是这样的-它删除重复的值并将其替换为相同的对象,但是添加了一个新的键,称为count,其值是对象最初的次数在数组中:
so what I would want my end result to be would be something like this - it removes the duplicate value and replaces it with the same object but adds a new key called count with a value of the number of times the object initially was in the array:
[
{ _id: "5971df93bfef201237985c4d",
slug: "5971df93bfef201237985c4d",
taxPercentage: 23,
totalCost: 9.99,
currency: "EUR",
count: 2, // whatever the count is
},
]
到目前为止,我正在使用此方法:
So far I'm using this method:
var count = [];
var count = [];
if (cart.cart.products != undefined) {
let namestUi = {
renderNames(names){
return Array.from(
names.reduce( (counters, object) =>
counters.set(object._id, (counters.get(object._id) || 0) + 1),
new Map() ),
([object, count]) => {
var filterObj = names.filter(function(e) {
return e._id == object;
});
return ({filterObj, count})
}
);
}
};
count = namestUi.renderNames(cart.cart.products);
console.log(count)
}
但是它返回的值是这样的:
but it returns the values like this:
{filterObj: Array // the array of the duplicates, count: 2}
{filterObj: Array, count: 1}
并且由于我在列表视图中使用React-Native,所以类似的东西将无法工作.
and since I am using React-Native with a list view something like this won't work.
它只需要以以前的方式(数组)存储项目,但有一个名为count
的新子代.
It just needs to store the items the way it was before (an array) but with a new child called count
.
欢迎任何帮助!
推荐答案
我会坚持使用reduce
,使用Map
并传播其values
以获得最终结果:
I would stick to reduce
, use a Map
and spread its values
to get the final result:
const names = [{ _id: 1 }, { _id: 1}, { _id: 2}, { _id: 1}];
const result = [...names.reduce( (mp, o) => {
if (!mp.has(o._id)) mp.set(o._id, { ...o, count: 0 });
mp.get(o._id).count++;
return mp;
}, new Map).values()];
console.log(result);
或者您可以首先使用零计数(使用Map构造函数)在地图中创建所有键,然后再次迭代数据以更新计数器.与reduce
相比,此任务拆分使代码更简洁:
Or you can first create all the keys in the map with a zero count (using the Map constructor), and then iterate the data again to update the counter. This split of tasks makes the code more concise than with reduce
:
const names = [{ _id: 1 }, { _id: 1}, { _id: 2}, { _id: 1}];
const mp = new Map(names.map(o => [o._id, {...o, count: 0 }]));
for (const {_id} of names) mp.get(_id).count++;
const result = Array.from(mp.values());
console.log(result);
当您拥有多个按键时,一个想法是使用JSON.stringify([ ])
将它们加入:
When you would have more than one key, then one idea is to join those with JSON.stringify([ ])
:
const names = [{cat: 1, sub: 1}, {cat: 1, sub: 2}, {cat: 2, sub: 1}, {cat: 1, sub: 1}];
const result = [...names.reduce( (mp, o) => {
const key = JSON.stringify([o.cat, o.sub]);
if (!mp.has(key)) mp.set(key, { ...o, count: 0 });
mp.get(key).count++;
return mp;
}, new Map).values()];
console.log(result);
这篇关于Javascript-计算对象数组中的重复项并将计数存储为新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!