You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并两个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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 20:36:02