0

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?

1
  • Why Lodash? Just Object.assign Commented Jul 27, 2018 at 4:49

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks mate! Very short and concise.
1

As alternative, if you prefer to not change the original object (immutable way), you can use ES6 spread operator.

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);

1 Comment

Object.assign and _.assign already support doing this without mutating the original object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.