我需要能够在运行时合并两个(非常简单的)JavaScript对象.例如,我想:

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

obj1.merge(obj2);

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

有没有一种内在的方法可以做到这一点?我不需要递归,也不需要合并函数,只需要平面对象上的方法.

推荐答案

ECMAScript 2018 Standard Method

你可以使用object spread:

let merged = {...obj1, ...obj2};

merged现在是obj1obj2的和.obj2中的属性将覆盖obj1中的属性.

/** 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};

下面也是此语法的MDN documentation.如果你使用的是巴别塔,你需要babel-plugin-transform-object-rest-spread插件才能工作.

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);

(见MDN JavaScript Reference)


Method for ES5 and Earlier

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

请注意,这将简单地添加obj2obj1的所有属性,如果您仍然想要使用未修改的obj1,那么这些属性可能不是您想要的.

如果你使用的框架在你的原型上到处都是垃圾,那么你必须通过hasOwnProperty这样的判断来获得更丰富的知识,但这些代码将适用于99%的情况.

示例功能:

/**
 * 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;
}

Javascript相关问答推荐

reaction useEffect KeyDown for each 条目配音输出

过滤对象数组并动态将属性放入新数组

通过嵌套模型对象进行Mongoose搜索

PrivateRoute不是路由组件错误

为什么Mutations 观察器用微任务队列而不是macrotask队列处理?

如果Arrow函数返回函数,而不是为useEffect返回NULL,则会出现错误

Web Crypto API解密失败,RSA-OAEP

在我的index.html页面上找不到我的Java脚本条形图

检索相加到点的子项

如何使用TypeScrip设置唯一属性?

如何在箭头函数中引入or子句?

使用插件构建包含chart.js提供程序的Angular 库?

有效路径同时显示有效路径组件和不存在的路径组件

如何在独立的Angular 应用程序中添加Lucide-Angel?

我为什么要使用回调而不是等待?

如何压缩图像并将其编码为文本?

无法在Adyen自定义卡安全字段创建中使用自定义占位符

我如何才能让p5.js在不使用实例模式的情况下工作?

相对于具有选定类的不同SVG组放置自定义工具提示

:host::ng-Deep不将样式应用于material 复选框