React Native中合并对象列表重复项并累加amount求助
React Native中按产品名称合并对象并累加amount总和
我是一名学习React Native的学生,需要合并一个对象列表,按产品名称累加对应的amount值,同时去除重复项。
原始数据
[ { "amount": 125, "amountUnit": "gr", "productID": { "jumboID": [], "name": "Tarwebloem" } }, { "amount": 1, "amountUnit": "tl", "productID": { "jumboID": [], "name": "Zonnebloem olie" } }, { "amount": 3, "amountUnit": "st", "productID": { "jumboID": [], "name": "Eieren" } }, { "amount": 1, "amountUnit": "tl", "productID": { "jumboID": [], "name": "Zonnebloem olie" } }, { "amount": 125, "amountUnit": "gr", "productID": { "jumboID": [], "name": "Tarwebloem" } }, { "amount": 3, "amountUnit": "st", "productID": { "jumboID": [], "name": "Eieren" } }, { "amount": 125, "amountUnit": "gr", "productID": { "jumboID": [], "name": "Tarwebloem" } }, { "amount": 1, "amountUnit": "tl", "productID": { "jumboID": [], "name": "Zonnebloem olie" } }, { "amount": 1, "amountUnit": "tl", "productID": { "jumboID": [], "name": "Zonnebloem olie" } }, { "amount": 3, "amountUnit": "st", "productID": { "jumboID": [], "name": "Eieren" } }, { "amount": 125, "amountUnit": "gr", "productID": { "jumboID": [], "name": "Tarwebloem" } } ]
期望结果
[ { "amount": 500, "amountUnit": "gr", "productID": { "jumboID": [], "name": "Tarwebloem" } }, { "amount": 4, "amountUnit": "tl", "productID": { "jumboID": [], "name": "Zonnebloem olie" } }, { "amount": 9, "amountUnit": "st", "productID": { "jumboID": [], "name": "Eieren" } } ]
解决方案
可以使用JavaScript的reduce方法实现需求,核心逻辑是用产品名称作为唯一标识,累加对应amount值:
const originalList = [/* 上述原始数据数组 */]; const mergedList = Object.values( originalList.reduce((acc, item) => { const productName = item.productID.name; // 若产品已存在,累加amount if (acc[productName]) { acc[productName].amount += item.amount; } else { // 不存在则新增项,浅拷贝避免修改原始数据 acc[productName] = { ...item }; } return acc; }, {}) ); // 输出合并后的结果 console.log(mergedList);
逻辑说明
- 用
reduce初始化一个空对象作为累加器,遍历原始列表 - 以产品名称为key,判断累加器中是否存在该产品
- 存在则累加amount,不存在则将当前项浅拷贝后存入累加器
- 最后用
Object.values()将累加器的value提取为数组,得到合并结果
内容的提问来源于stack exchange,提问作者Murat
相关产品推荐
相关产品推荐

