我有一组作为产品的 javascript 对象。这些产品作为购物车显示在列表中。
我想根据 _.id
值计算数组中重复产品的数量,然后从数组中删除这些对象,并用更新版本和名为 的新键替换它们>count
这个对象出现的总次数。
到目前为止,我已经尝试了很多方法,并且在谷歌上进行了搜索,但我发现没有任何方法可以正确完成这项工作。
我将使用的数组类型示例如下:
[
{ _id: "5971df93bfef201237985c4d",
slug: "5971df93bfef201237985c4d",
taxPercentage: 23,
totalCost: 9.99,
currency: "EUR",
},
]
所以我希望我的最终结果是这样的——它删除了重复的值并用同一个对象替换它,但添加了一个名为 count 的新键,其值是对象最初出现的次数在数组中:
[
{ _id: "5971df93bfef201237985c4d",
slug: "5971df93bfef201237985c4d",
taxPercentage: 23,
totalCost: 9.99,
currency: "EUR",
count: 2, // whatever the count is
},
]
到目前为止,我正在使用这种方法:
变量计数 = [];
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)
}
但它返回的值是这样的:
{filterObj: Array // the array of the duplicates, count: 2}
{filterObj: Array, count: 1}
并且因为我使用的是带有 ListView 的 React-Native,所以这样的东西是行不通的。
它只需要像以前一样存储项目(一个数组),但有一个名为 count
的新 child 。
欢迎任何帮助!
最佳答案
我会坚持使用 reduce
,使用 Map
并传播它的 values
以获得最终结果:
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);
或者您可以先用零计数创建映射中的所有键(使用映射构造函数),然后再次迭代数据以更新计数器。这种任务拆分使代码比 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);
当您拥有多个 key 时,一个想法是使用 JSON.stringify([ ])
加入这些 key :
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 - 计算对象数组中的重复项并将计数存储为新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45258566/