简体   繁体   中英

Initializing a JavaScript object with the values of another JavaScript object

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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