TypeScript中如何将对象数组转换为单个对象?
TypeScript中将对象数组合并为单个对象的实现方法
下面是几种常用的实现方式,根据场景选择即可:
方法一:使用Object.assign()
Object.assign()可将多个源对象的属性合并到目标对象中,配合扩展运算符展开数组元素,就能快速合并整个数组的对象:
const myArray = [ {itemOneKey: 'itemOneValue', itemTwoKey: 'itemTwoValue'}, {itemThreeKey: 'itemThreeValue'} ]; const myObject = Object.assign({}, ...myArray);
这里传空对象作为目标,避免修改原数组中的对象,后续展开数组里的每个对象作为源对象,最终得到合并后的单个对象。
方法二:使用对象扩展运算符(...)
直接通过扩展运算符把数组中所有对象的属性展开到新对象里:
const myArray = [ {itemOneKey: 'itemOneValue', itemTwoKey: 'itemTwoValue'}, {itemThreeKey: 'itemThreeValue'} ]; const myObject = {...(...myArray)};
如果数组长度固定,也可以逐个展开:
const myObject = {...myArray[0], ...myArray[1]};
方法三:使用Array.reduce()
如果需要更灵活的处理逻辑(比如自定义重复键的处理规则),可以用reduce遍历数组并逐步合并:
const myArray = [ {itemOneKey: 'itemOneValue', itemTwoKey: 'itemTwoValue'}, {itemThreeKey: 'itemThreeValue'} ]; const myObject = myArray.reduce((accumulator, current) => { return {...accumulator, ...current}; }, {});
初始值设为空对象{},每次迭代把当前对象的属性合并到累加器中,最终返回完整的合并对象。
注意事项
如果数组中的对象存在相同属性名,后面对象的属性值会覆盖前面的,这是JavaScript/TypeScript对象的固有特性(键名唯一)。
内容的提问来源于stack exchange,提问作者Lonwabo Rarane
相关产品推荐
相关产品推荐

