AndrewBrntt
AndrewBrntt

Reputation: 1722

React merge immutable array of objects using React Immutability helpers or Immutable js

I am trying to merge an immutable array of objects using Reacts Immutability helpers or Immutable js which ever one. I am trying to create a list of only records where the names have changed. I am trying to avoid creating duplicates in the list if the name has been changed multiple times before submission which lead me to believe a merge was the path I needed to take. An example of what I am trying to achieve is below.

 var objArray = [{id:4, name:'bar'}, {id:10, name:'test'}];
 var newObj = {id:4, name:'foo'};

 var updatedEntries = update(this.state.nameChanges, {$merge: {newObj});

The Result I am looking for is:

 objArray = [{id:4, name:'foo'}, {id:10, name:'test'}]

The Result I seem to be getting is:

 objArray = [{id:4, name:'foo'}]

I have tried using Facebook React immutability helpers but cannot seem to get the result I need. I seem to be having a little trouble trying wrapping my head around what the merge function is actually doing. Any help is appreciated.

Thanks

Upvotes: 2

Views: 3880

Answers (1)

Henrik Andersson
Henrik Andersson

Reputation: 47172

You're almost there, what you need to do is to first filter out the object you want and then using merge via its index in the objArray. The official docs shows how to do this

var objArray = [{id: 4, name: 'bar'}, {id: 10, name: 'test'}];

var i = -1;
objArray.map(function (obj, index) {
  if (obj.name === 'bar') i = index;
});

var mergeObject = {};
mergeObject[i] = {$merge: {name: 'Foo'}};

var newState = update(objArray, mergeObject);

>>  [[object Object] {
  id: 4,
  name: "Foo"
}, [object Object] {
  id: 10,
  name: "test"
}]

Upvotes: 2

Related Questions