0

So we have an empty JavaScript object, and we want to initialize its keys with the value of another object which has only some of the key-values from the first object, without changing the values of the other keys. Is there any library that can pull this off?

The Empty object : {'name' : 'John' , 'lastName' : ' '}

The second object: {'name' : 'Alex'}

The desired output : {'name':'Alex', 'lastName' : ' '}

Fyi: I know that this can be implemented with a bunch of ifs and for loops, but I wanted to know if there was a library that can do this in a better way.

2

1 Answer 1

1

You'd be best with

var desiredOutput = Object.assign({}, emptyJson, secondJson);

It takes the target (first argument) and assigns values from the sources (second argument, and third and so on... Whenever the key does exist on target object, it's value gets overwritten by the value of source object. Otherwise key: value pair is added.

In our case, we use empty object ({}) as a target attribute, not to overwrite source's properties.

There's no support for Internet Explorer so if you have to support it, there's a polyfill available.

You can find more details and polyfill on MDN Docs

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

Comments

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.