简体   繁体   中英

Javascript ES6, how to add value to array inside a newly copied object?

in ES6 there is a new way to copy objects so you can have a nice way to handle inmutable states:

let oldObj = { foo: 1}; // { foo: 1 }

let newObj = { ...oldObj, bar: 2 }; // { foo: 1, bar: 2}

However what I want to achieve is:

let oldObj = { foo: [1] }; // { foo: [1] }

let newObj = ??? // { foo: [1, 2] }

Any idea on how to achieve this?

let newObj = { foo: [...oldObj.foo, 2] }

你也可以看看 Immutable js - http://facebook.github.io/immutable-js

I like Zerkms answer a bit better because it is more general, if your object contains more keys other than the array:

{ ...oldObj, foo: [...oldObj.foo, 2] }

Credit to @Zerkms.

you can use dynamic value [...oldObj.foo, bar]

 let oldObj = { foo: [1] }; // { foo: [1] } let newObj = { ...oldObj, foo: [1, 2] } // { foo: [1, 2] } console.log(newObj) let oldObj2 = { foo: [1] }; // { foo: [1] } let bar = 2 let newObj2 = { foo: [...oldObj.foo, bar] } // { foo: [1, 2] } console.log(newObj2)

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