JavaScript中合并对象数组到目标对象如何避免生成数组索引键?
问题原因
直接将数组通过展开运算符(...)插入对象时,JS会将数组的数字索引作为新对象的键名,因此会生成0、1这类不符合预期的键。你需要先将数组内所有子对象合并为一个总对象,再和其他属性合并。
解决方案1:使用Object.assign直接合并(最简洁)
Object.assign 支持接收多个对象作为入参,会将后续所有对象的属性合并到第一个参数对象中,直接将orderList数组展开作为入参即可:
const orderList = []; orderList.push({ order1: { desc: "smt1" } }) orderList.push({ order2: { desc: "smt2" } }) const result = Object.assign( { anotherVar1: 1, anotherVar2: 2 }, ...orderList ) console.log("result", result)
输出结果和你预期完全一致。
解决方案2:使用reduce预处理数组合并
如果合并过程中需要添加自定义判断逻辑,可以先用reduce将订单数组转为单个对象,再展开合并:
// 先合并数组成单个订单对象 const mergedOrders = orderList.reduce((prev, curr) => ({...prev, ...curr}), {}) const result = { anotherVar1: 1, anotherVar2: 2, ...mergedOrders }
内容的提问来源于stack exchange,提问作者Luis Febro
相关产品推荐
相关产品推荐

