回答

收藏

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

技术问答 技术问答 177 人阅读 | 0 人回复 | 2023-09-11

运行时需要能够合并两个(非常简单)JavaScript 对象。比如我想:+ q* G" D! ]) D/ f) `9 O
    var obj1 = { food: 'pizza',car: 'ford' }var obj2 = { animal: 'dog' }obj1.merge(obj2);//obj1 now has three properties: food,car,and animal
    - }, X; A! R" _3 p* ]4 g, ^
有没有内置的方法可以做到这一点?我不需要递归或合并函数,只需要平面对象上的方法。; ?; b3 M$ L" Z; K% i
                                                                . J4 K4 h( m/ c4 _3 j( O( e- t
    解决方案:                                                                & B5 E# ~& E; p. }) o* C5 ~
                                                                ECMAScript 2018年 标准方法% C9 F+ X9 x' b4 H
用对象传播:
) v/ q5 H2 |- O. B) X. X" ^
    let merged = {...obj1,...obj2};
    2 d% B. p4 T% ]# w$ b7 q. ^
merged现在是 和 obj1并集obj2。中的属性obj2将覆盖obj1.
! M( V  S0 O! d
    /** 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};
    ( S6 J) C+ e# {1 _6 W6 i
这也是语法MDN如果使用 文档。babel,你需要babel-plugin-transform-object-rest-spread只有插件才能工作。
- z/ ]& N4 K+ }) J; Z7 l" {+ a7 eECMAScript 2015 (ES6) 标准方法; Y! \6 o4 ?. i- f3 V& y
    /* 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);
    + U/ d. q% s+ u& f) X6 _
(见MDN JavaScript 参考)2 T/ S$ P6 l; ?5 e4 H, D
ES5 及早版本的方法8 }, [% \! ^( Q6 m8 Q; m6 W6 a
    for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }+ E3 ^* O7 i' @0 {: K( Y9 x
请注意,如果您仍然想使用未修改的产品obj2的.obj1``obj1* |/ l$ m+ f3 E3 A( c7 A$ j* h' \
如果你使用的框架在你的原型上是废话,你必须通过类似的检查获得更好的体验hasOwnProperty,但该代码将适用于 99% 。
) w4 [9 v$ c! d: c" r示例函数:0 u5 s2 C! c& R. R# ]" L
    /** * 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,obj二、{     var obj3 = {};    for (var attrname in obj1) { obj3[attrname] = obj1[attrname];    for (var attrname in obj2) { obj3[attrname] = obj2[attrname];    return obj3;}
    , e- X) S5 Q* m" Y5 I
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则