1

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?

5
  • 1
    { ...oldObj, foo: [...oldObj.foo, 2] } --- no easy way here. PS: the syntax you're referring to is not "ES6" and is not even standardised yet. Commented Jul 21, 2016 at 2:08
  • ah, is it babel then? Commented Jul 21, 2016 at 2:12
  • github.com/sebmarkbage/ecmascript-rest-spread --- it is a stage-2 proposal Commented Jul 21, 2016 at 2:14
  • good to know, thank you for the quick reply Commented Jul 21, 2016 at 2:15
  • 1
    just to clarify, spread operator is part of ES6 for Arrays, just not for Objects - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jul 21, 2016 at 2:27

3 Answers 3

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

You could also have a look at Immutable js - http://facebook.github.io/immutable-js

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

Comments

1

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.

Comments

0

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)

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.