使用 JavaScript 的 reduce 方法可以轻松地合并数组对象,根据 ID 合并相同对象,并将相同属性值进行相加,并将字符串 push 到数组中。以下代码演示了如何实现:\n\njavascript\nconst arr = [\n { id: 1, num: 1, scanCode: 'A' },\n { id: 1, num: 2, scanCode: 'B' },\n { id: 2, num: 1, scanCode: 'C' },\n { id: 3, num: 1, scanCode: 'D' },\n { id: 3, num: 2, scanCode: 'E' },\n { id: 3, num: 1, scanCode: 'F' }\n];\n\nconst mergedArr = Object.values(arr.reduce((acc, curr) => {\n const key = curr.id;\n if (acc[key]) {\n const existingObj = acc[key];\n existingObj.num += curr.num;\n existingObj.scanCode.push(curr.scanCode);\n } else {\n acc[key] = { ...curr, scanCode: [curr.scanCode] };\n } \n return acc;\n}, {}));\n\nconsole.log(mergedArr);\n\n\n输出结果为:\n\njavascript\n[\n { id: 1, num: 3, scanCode: ['A', 'B'] },\n { id: 2, num: 1, scanCode: ['C'] },\n { id: 3, num: 4, scanCode: ['D', 'E', 'F'] }\n]\n\n\n代码通过 reduce 方法遍历数组,使用 id 作为键值,将相同 id 的对象合并并相加相同 num 的属性,并将 scanCode 字符串 push 到数组中。最后通过 Object.values 方法将结果转换为数组形式。\n\n本教程提供了清晰的代码示例和详细的解释,可以帮助你理解如何使用 reduce 方法合并数组对象。

JavaScript 数组对象合并:根据 ID 合并相同对象,相加相同属性值,并将字符串 push 到数组

原文地址: https://www.cveoy.top/t/topic/qeS0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录