
本文探讨如何根据id和name字段合并javascript数组中的重复对象。
问题描述
给定一个包含多个对象的JavaScript数组,如何将具有相同id和name属性的对象合并,并将重复的list属性值整合到一个数组中?
示例代码
假设我们有以下数组arr:
立即学习“Java免费学习笔记(深入)”;
<code class="javascript">const arr = [
{ id: 1, name: '小明', list: { id: 66 } },
{ id: 1, name: '小红', list: { id: 44 } },
{ id: 2, name: '小绿', list: { id: 55 } },
{ id: 2, name: '小绿', list: { id: 33 } },
{ id: 3, name: '小紫', list: { id: 11 } },
{ id: 3, name: '小紫', list: { id: 22 } }
];</code>期望结果
合并后的数组应如下所示:
<code class="javascript">const expectedResult = [
{ id: 1, name: '小明', list: { id: 66 } },
{ id: 1, name: '小红', list: { id: 44 } },
{ id: 2, name: '小绿', list: [{ id: 55 }, { id: 33 }] },
{ id: 3, name: '小紫', list: [{ id: 11 }, { id: 22 }] }
];</code>解决方案
我们可以利用reduce方法高效地实现这一目标:
<code class="javascript">const mergedArray = Object.values(arr.reduce((acc, { id, name, list }) => {
const key = `${id}-${name}`; // 使用id和name组合成唯一的key
if (!acc[key]) {
acc[key] = { id, name, list: [] };
}
acc[key].list.push(list);
return acc;
}, {}));</code>这段代码首先使用reduce方法遍历数组,并根据id和name的组合生成唯一的键值。 如果该键值不存在,则创建一个新的对象并将list属性初始化为一个空数组。然后,将当前对象的list属性添加到对应的数组中。最后,Object.values方法将结果对象转换为数组。
此方法避免了嵌套循环,提高了代码效率,尤其在处理大型数组时优势明显。 它清晰地实现了根据id和name字段合并对象,并正确地处理了list属性的整合。
以上就是JavaScript数组对象合并:如何根据ID和name字段合并重复对象?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号