0

I have the following state object

campaigns : [
  {
    id : 1,
    active: false,
    ....other key value pairs
  },
  {
    id : 2,
    active: false
    ....other key value pairs
  },
  {
    id : 3,
    active: false
    ....other key value pairs
   }
]

My api gives me a response of the campaign id (say for example 2) how do i change the active flag to true in the campaigns array without mutating it or using a library. Es6 or just plain JS. Any help would be good.

I am using just react and react router.. not redux as yet.

Nitish Phanse
  • 552
  • 1
  • 9
  • 16
  • 2
    Object properties are mutable. If you want immutibility, copy the array to a new array and change it there. – Sterling Archer Oct 19 '16 at 15:59
  • 2
    "I want to change x without mutating x" is nonsensical. "mutate" == "change" – drew moore Oct 19 '16 at 16:00
  • So, just to be clear, these objects are stored in both the `campaigns` array and somewhere else, and you want to change the value in `campaigns` without changing the other references? Basically, you want to replace the object in `campaigns` with a (deep?) copy of itself, then mutate the copy, leaving other references unchanged? If so, take a look at [What is the most efficient way to deep clone an object in JavaScript?](http://stackoverflow.com/q/122102/364696). Or am I completely misunderstanding? As the other comments note, "changing without mutating" makes no sense on its face. – ShadowRanger Oct 19 '16 at 16:01
  • Thanks that worked ^ – Nitish Phanse Oct 19 '16 at 17:07

1 Answers1

0

You can use Object.assign to make a clone of whatever the object is. It will make its own reference and any changes made to it wont impact the original object. var copy = Object.assign({}, obj)

Object.assign is only a shallow copy meaning if you have a nested object it will still share the same reference to those values with the original object. Looking at your object structure that shouldn't be a problem though.

finalfreq
  • 6,830
  • 2
  • 27
  • 28
  • Note: [`Object.assign` is not supported in IE (though all other modern browsers, including Edge, support it)](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Browser_compatibility). So if you're writing web pages for arbitrary browsers, using it will break for [10-15% of users](https://en.wikipedia.org/wiki/Usage_share_of_web_browsers#Summary_tables). – ShadowRanger Oct 19 '16 at 16:38