YaoRaoLov 2008-10-05 00:30 采纳率: 50%
浏览 1124
已采纳

如何动态合并两个 JavaScript 对象的属性?

I need to be able to merge two (very simple) JavaScript objects at runtime. For example I'd like to:

var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog' }

obj1.merge(obj2);

//obj1 now has three properties: food, car, and animal

Does anyone have a script for this or know of a built in way to do this? I do not need recursion, and I do not need to merge functions, just methods on flat objects.

转载于:https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically

  • 写回答

20条回答 默认 最新

  • ℙℕℤℝ 2014-01-27 21:00
    关注

    ECMAScript 2018 Standard Method

    You would use object spread:

    let merged = {...obj1, ...obj2};
    
    /** There's no limit to the number of objects you can merge.
     *  Later properties overwrite earlier properties with the same name. */
    const allRules = {...obj1, ...obj2, ...obj3};
    

    ECMAScript 2015 (ES6) Standard Method

    /* For the case in question, you would do: */
    Object.assign(obj1, obj2);
    
    /** There's no limit to the number of objects you can merge.
     *  All objects get merged into the first object. 
     *  Only the object in the first argument is mutated and returned.
     *  Later properties overwrite earlier properties with the same name. */
    const allRules = Object.assign({}, obj1, obj2, obj3, etc);
    

    (see MDN JavaScript Reference)


    Method for ES5 and Earlier

    for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }
    

    Note that this will simply add all attributes of obj2 to obj1 which might not be what you want if you still want to use the unmodified obj1.

    If you're using a framework that craps all over your prototypes then you have to get fancier with checks like hasOwnProperty, but that code will work for 99% of cases.

    Example function:

    /**
     * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
     * @param obj1
     * @param obj2
     * @returns obj3 a new object based on obj1 and obj2
     */
    function merge_options(obj1,obj2){
        var obj3 = {};
        for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
        for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
        return obj3;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(19条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配