JavaScript处理两个对象数组:编写转换与求和函数
解决方案:更新数组数值并按指定键求和
实现代码
function processArrays(arr1, arr2) { // 构建address到value的映射,快速查找匹配值 const addressValueMap = Object.fromEntries( arr2.map(item => [item.address, item.value]) ); // 更新arr1的value字段 const arr1After = arr1.map(item => ({ ...item, value: addressValueMap[item.address] || item.value })); // 统计每个addKey对应的value总和 const addKeyTotalMap = arr1After.reduce((acc, item) => { acc[item.addKey] = (acc[item.addKey] || 0) + item.value; return acc; }, {}); // 更新arr2的total字段 const arr2After = arr2.map(item => ({ ...item, total: addKeyTotalMap[item.address] || 0 })); return { arr1After, arr2After }; } // 示例调用 const arr1 = [ { addKey: '11', address: '12', value: 0 }, { addKey: '11', address: '12', value: 0 }, { addKey: '12', address: '11', value: 0 }, { addKey: '12', address: '11', value: 0 }, ]; const arr2 = [ {address: '11', value: 5, total: 0 }, {address: '12', value: 10, total: 0 }, ]; const result = processArrays(arr1, arr2); console.log('arr1After:', result.arr1After); console.log('arr2After:', result.arr2After);
代码逻辑说明
- 步骤1:构建快速查找映射
把arr2转换成以address为键、value为值的对象,避免每次匹配都遍历arr2,提升处理效率。 - 步骤2:更新arr1的value
遍历arr1的每个元素,复制原元素(不修改原数组),根据address从映射中取出对应值赋值给value字段。 - 步骤3:统计addKey的总和
用reduce遍历更新后的arr1,累加每个addKey对应的value总和,生成addKey到总和的映射。 - 步骤4:更新arr2的total
遍历arr2的每个元素,复制原元素,根据address(对应arr1的addKey)从总和映射中取出值赋值给total字段。
内容的提问来源于stack exchange,提问作者valdimar.ein
相关产品推荐
相关产品推荐

