JS中如何基于键映射实现普通对象与数组对象的合并
需求说明
基于对象键与数组内对象的field键映射关系,将单个源对象的键值对合并到目标数组的对应对象中。
原示例存在语法错误,修正后的参考结构如下:
// 待合并源对象 const sourceObj = { id: 49, city: 'bangalore', country: 'India' } // 目标数组(移除原示例多余的嵌套大括号,修正为合法数组结构) const targetArr = [ {title: 'Location ID', field: 'id', width: 200, _width: 200, filter: 'text'}, {title: 'City', field: 'city', width: 200, _width: 200, filter: 'dropdown'}, {title: 'Country', field: 'country', width: 200, _width: 200, filter: 'dropdown'} ]
预期输出结构:
[ {id: 49, title: 'Location ID', field: 'id', width: 200, _width: 200, filter: 'text'}, {city: 'bangalore', title: 'City', field: 'city', width: 200, _width: 200, filter: 'dropdown'}, {country: 'India', title: 'Country', field: 'country', width: 200, _width: 200, filter: 'dropdown'} ]
错误写法原因
你使用的console.log([...Obj,...arr])存在两个核心问题:
- 普通对象不是可迭代结构,直接在数组字面量中用
...展开对象会直接抛出语法错误 - 就算将对象转为可迭代结构再展开,也只是把对象的属性平铺为数组的独立元素,无法实现按field键匹配后合并到对应数组项的逻辑。
正确实现方案
遍历目标数组,对每一项取其field值作为匹配键,从源对象中取出对应值,和当前项的属性合并即可:
const mergedResult = targetArr.map(item => ({ [item.field]: sourceObj[item.field], ...item })) console.log(mergedResult)
运行后输出的结构和预期完全一致。
内容的提问来源于stack exchange,提问作者Jay
相关产品推荐
相关产品推荐

