Search code examples
javascriptjsonnode.jsecmascript-6lodash

How to replace or append object to another object using Lodash


I have 2 objects

{
    "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?


Solution

  • You don't need lodash for it. Use Object.assign to do that in plain JS. It works for the second case as well.

    And if you really want to do it with lodash, use _.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);