gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:39:22 24 4
gpt4 key购买 nike

我需要能够在运行时合并两个(非常简单的)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 标准方法

您将使用object spread :

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

merged现在是 obj1 的并集和obj2 。属性 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,您将需要 @babel/plugin-proposal-object-rest-spread使其工作的插件(此插件包含在 @babel/preset-envES2018 中)。

ECMAScript 2015 (ES6) 标准方法

/* 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 )

<小时/>

ES5 及更早版本的方法

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

请注意,这只会添加 obj2 的所有属性至obj1如果您仍然想使用未修改的 obj1 ,这可能不是您想要的。 .

如果你使用的框架在你的原型(prototype)上到处乱七八糟,那么你必须更喜欢像 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;
}
<小时/>

另外:- check this program查看 Object.assign 和 spread 语法对象字面量之间的差异

关于javascript - 如何动态合并两个 JavaScript 对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28240670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com