简体   繁体   中英

Can I add a couple of key-value pairs to a JavaScript object as literals in one line?

Say I have an object such as

var obj = {
  foo: 1,
  bar: 2
}

And I want to add a few more keys without making a loop, something semantically like this:

obj += { baz: 3, fred: 4 }

Is that possible using an existing JS function? I'd like to do it within some functional-style chaining.

Check if compatibility is a concern before doing this, but object destructuring to the rescue:

var obj = {
  foo: 1,
  bar: 2
}

obj = {...obj, baz: 3, fred: 4}

The following is not possible but we can dream:

obj ...= {beef: 5}

And right after posting my Googling became successful!

Apparently Object.assign arrived with ES6 and I'm really looking for modern JS answers.

var obj = {
  foo: 1,
  bar: 2
}

obj = Object.assign(obj, {baz:3, fred:4})

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