0

This is a babel/ES7 question (for redux reducer use)

I want to update "dan" only in some properties. What's the preferred way with immutability mind?

It seems that only TRY 1 and TRY 3 merge/update correctly.

Is there any difference between the two? For me TRY 3 wins because it's the shortest (if no difference between TRY 1)

Thanks

const people = { byID: {
    gaston : { name:'Gaston', age: 22 }, 
    dan : { name: 'gaston', age: 44 }
  } 
}

const currentID = "dan"

///
// TRY 1 

const thisID = {}
thisID[currentID] = {...people.byID[currentID],
  age: 20,
  sex: 'male',
}

const newPeople = {...people, 
  byID: {...people.byID,
    ...thisID
  }
}

console.log( newPeople  ) // OK

//
// TRY 2

const newPeople2 = {} 
newPeople2.byID = {}
newPeople2.byID[currentID] = {}
newPeople2.byID[currentID]["age"] = 20
newPeople2.byID[currentID]["sex"] = "male"

const newPeople3 = {...people, ...newPeople2}

console.log( newPeople3 )  // NOPE (not merge)

//
// TRY 3

const newPeople4 = {...people}
newPeople4.byID = newPeople4.byID || {} 
newPeople4.byID[currentID] = newPeople4.byID[currentID] || {} 
newPeople4.byID[currentID]["age"] = 20
newPeople4.byID[currentID]["sex"] = "male"

console.log(newPeople4) // OK

Here are the outputs

TRY 1 

{"byID":{"gaston":{"name":"Gaston","age":22},"dan":{"name":"gaston","age":20,"sex":"male"}}}

TRY 2

{"byID":{"dan":{"age":20,"sex":"male"}}}

TRY 3

{"byID":{"gaston":{"name":"Gaston","age":22},"dan":{"name":"gaston","age":20,"sex":"male"}}}
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
Gaston Morixe
  • 839
  • 2
  • 10
  • 21

1 Answers1

0

Using the spread operator, you can do:

const updatedPeople = {
  byID: {
    ...people.byID,
    dan: {
      ...people.byID.dan,
      age: 20,
      sex: "male"
    }
  }
};

If you need the id to be dynamic, using computed property keys (an other ES6 feature, part of destructuring):

const id = 'dan';

const updatedPeople = {
  byID: {
    ...people.byID,
    [id]: {
      ...people.byID[id],
      age: 20,
      sex: "male"
    }
  }
};

Those solutions are immutability full proof, though, if you're not familiar with ES6 syntax, they can be hard to read and if you have more complex data, you might consider using immutablejs (or some kind of immutable library)

topheman
  • 7,422
  • 4
  • 24
  • 33