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.