gpt4 book ai didi

javascript - 通过参数组合和分组 javascript 对象的最佳方法

转载 作者:行者123 更新时间:2023-11-29 16:06:11 25 4
gpt4 key购买 nike

我正在 React 中处理购物车页面,基本上我需要按产品名称对订单进行分组并包含数量。

所以...如果我的产品数组如下...

const items = [
{ title: 'Test', price: 1 },
{ title: 'Test', price: 1 },
{ title: 'Another Test', price: 3 },
]

我正在尝试获得类似...

const expected = [
{ title: 'Test', price: 1, quantity: 2 },
{ title: 'Another Test', price: 3, quantity: 1 },
]

我尝试了几种不同的方法,但并没有完全让我到达那里,包括使用 underscorejs 中的 groupBy,但没有快乐!

这是我正在摆弄的 JS fiddle :https://jsfiddle.net/rL8y3Lh4/2/

最佳答案

你可以使用 Map用于分组。

var items = [{ title: 'Test', price: 1 }, { title: 'Test', price: 1 }, { title: 'Another Test', price: 3 }],
grouped = items.reduce((map => (r, a) => {
if (!map.has(a.title)) {
map.set(a.title, { title: a.title, price: a.price, quantity: 0 });
r.push(map.get(a.title));
}
map.get(a.title).quantity++;
return r;
})(new Map), []);

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES5 在哈希表上有闭包。

var items = [{ title: 'Test', price: 1 }, { title: 'Test', price: 1 }, { title: 'Another Test', price: 3 }],
grouped = items.reduce(function (hash) {
return function (r, a) {
if (!hash[a.title]) {
hash[a.title] = { title: a.title, price: a.price, quantity: 0 };
r.push(hash[a.title]);
}
hash[a.title].quantity++;
return r;
};
}(Object.create(null)), []);

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 通过参数组合和分组 javascript 对象的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41837815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com