如何合并两个JavaScript对象的值生成指定键值结构的新对象
实现方案
你可以通过遍历两个对象的共有属性,将customers的属性值作为新对象的键,members的对应属性值作为新对象的值实现,下面给出两种常用实现方式:
方法1:使用reduce实现(推荐,写法简洁)
let members = { first_name: "sagar", last_name: "phani", birth_date: "31-06-1996", } let customers = { first_name: "MERGE31", last_name: "MERGE32", birth_date: "MERGE33" } const result = Object.keys(members).reduce((acc, curKey) => { acc[customers[curKey]] = members[curKey] return acc }, {}) console.log(result) // 输出 {MERGE31: 'sagar', MERGE32: 'phani', MERGE33: '31-06-1996'}
方法2:使用for...in循环实现(兼容性更好,易理解)
const result = {} // 遍历members的所有自有属性 for (const key in members) { // 过滤原型链属性,同时确保customers上存在对应属性再赋值 if (Object.prototype.hasOwnProperty.call(members, key) && Object.prototype.hasOwnProperty.call(customers, key)) { result[customers[key]] = members[key] } }
注意事项
如果两个对象的属性不是完全匹配的,可以在遍历逻辑中增加自定义过滤规则,处理属性缺失的场景。
内容的提问来源于stack exchange,提问作者Sagar P
相关产品推荐
相关产品推荐

