如何将对象数组合并为单个对象且重复键以最后出现值为准
对象数组合并为单个对象的实现方案
核心逻辑:按顺序遍历数组内所有对象,依次合并属性到目标对象,后出现对象的同键属性自动覆盖前面对象的对应值。
JavaScript 实现
极简写法
利用Object.assign()的合并特性,直接将数组展开作为参数传入,天然匹配后值覆盖前值的规则:
const input = [ { '1112225544': '1', '3258458756': '9', '3654125412': '5', }, { '2229993827': '0', '9827719902': '1', '0000000000': '2', '1112225544': '3', } ]; // 合并后结果即为所需的单个对象 const result = Object.assign({}, ...input);
兼容性写法
使用reduce遍历实现,适配低版本运行环境:
const result = input.reduce((acc, current) => { // 遍历当前对象所有属性,逐个赋值到累计对象,自动覆盖旧值 for (const key in current) { if (current.hasOwnProperty(key)) { acc[key] = current[key]; } } return acc; }, {});
Python 实现
input_list = [ { '1112225544': '1', '3258458756': '9', '3654125412': '5', }, { '2229993827': '0', '9827719902': '1', '0000000000': '2', '1112225544': '3', } ] result = {} for item in input_list: result.update(item) # Python 3.9+ 可使用更简洁的运算符写法 from functools import reduce from operator import or_ result = reduce(or_, input_list, {})
内容的提问来源于stack exchange,提问作者codemonkey
相关产品推荐
相关产品推荐

