2

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

4
  • I'm not sure what you're update does, but merge works for me Commented Dec 8, 2015 at 19:36
  • @Tyrsius It's not ImmutableJS - it's the builtin variants that React ships with. Commented Dec 8, 2015 at 19:38
  • Oh, in that case I just showed you how to do it with ImmutableJS. Does that work? Commented Dec 8, 2015 at 19:40
  • No it does not if the array is empty its sets the values to undefined and if it is not empty it still just overwrites it and removes any other objects in the array except the new one. Commented Dec 8, 2015 at 20:18

1 Answer 1

2

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"
}]
Sign up to request clarification or add additional context in comments.

3 Comments

Little more code then I expect there to be but yeah that is what I need thanks
I was being overly verbose, you can use map as a fancy iterator and a variable to close over the index. I've updated the code a bit. But since you want to define a dynamic key on the merge you need to make that intermediary object.
Is there any better solution? is there any other library which does this?

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.