![](/img/trans.png)
[英]How to replace the object with the new object using javascript or lodash?
[英]How to replace or append object to another object using Lodash
我有2個物件
{
"Simon": {
"occupation": "garbage man",
"age": "21"
}
}
還有這個
{
"wife": "Kate"
}
我如何將第二個對象插入第一個對象以得到
{
"Simon": {
"occupation": "garbage man",
"age": "21",
"wife": "Kate"
}
}
並且即使妻子存在也可以適用:
{
"wife": "Shandia"
}
結果到
{
"Simon": {
"occupation": "garbage man",
"age": "21",
"wife": "Shandia"
}
}
有沒有一種方法可以使用lodash做到這一點?
您不需要lodash。 使用Object.assign
在普通JS中執行此操作。 它也適用於第二種情況。
如果您真的想用lodash來做,請使用_.assign
; 它的工作原理是一樣的。
var simon = { "Simon": { "occupation": "garbage man", "age": "21" } } var wife = { "wife": "Shandia" }; Object.assign(simon.Simon, wife); console.log(simon);
作為替代方案,如果您不想更改原始對象(不變的方式),則可以使用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.