简体   繁体   English

如何使用Lodash将对象替换或附加到另一个对象

[英]How to replace or append object to another object using Lodash

I have 2 objects 我有2个物件

{
    "Simon": { 
        "occupation": "garbage man",
        "age": "21"
    }
}

and this one 还有这个

{
    "wife": "Kate"
}

How will I insert the second object to the first object to result as 我如何将第二个对象插入第一个对象以得到

{
    "Simon": { 
        "occupation": "garbage man",
        "age": "21",
        "wife": "Kate"
    }
}

And also can be applied even when wife exists: 并且即使妻子存在也可以适用:

{
    "wife": "Shandia"
}

Results to 结果到

{
    "Simon": { 
        "occupation": "garbage man",
        "age": "21",
        "wife": "Shandia"
    }
}

Is there a way to achieve this using lodash? 有没有一种方法可以使用lodash做到这一点?

You don't need lodash for it. 您不需要lodash。 Use Object.assign to do that in plain JS. 使用Object.assign在普通JS中执行此操作。 It works for the second case as well. 它也适用于第二种情况。

And if you really want to do it with lodash, use _.assign ; 如果您真的想用lodash来做,请使用_.assign ; it works the same. 它的工作原理是一样的。

 var simon = { "Simon": { "occupation": "garbage man", "age": "21" } } var wife = { "wife": "Shandia" }; Object.assign(simon.Simon, wife); console.log(simon); 

As alternative, if you prefer to not change the original object (immutable way), you can use ES6 spread operator. 作为替代方案,如果您不想更改原始对象(不变的方式),则可以使用ES6传播算子。

 var simon = { "Simon": { "occupation": "garbage man", "age": "21" } } var wife = { "wife": "Shandia" }; const simonWithWife = { Simon: { ...simon.Simon, ...wife } } console.log(simon); // doesn't get changed console.log(simonWithWife); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM