eveo
eveo

Reputation: 2833

Update Immutable List with only new data that doesn't match prior nested keys?

I have an immutableJS List which I would like to append to only if the new data's location.name does not match my prior data's location.name.

I get initial data into the List in this format (new data is in the same format, an array of objects):

[  
  {  
    "location": {  
      "name":"A String"
    }
  },
  {  
    "location": {  
      "name":"A String 2"
    }
  }
]

However, any subsequent data, I'd like to append to this array of objects ONLY if the location name doesn't match any prior location names that already exist in the state.

Currently I'm returning the state as such but there is a lot of repetition in this approach.

case RECEIVE_LOCATIONS:
  return state
    .set('stores', state.get('stores').update(fromJS(action.locations)))

Upvotes: 0

Views: 87

Answers (1)

Sagi_Avinash_Varma
Sagi_Avinash_Varma

Reputation: 1509

you can filter out the repeated location items

case RECEIVE_LOCATIONS:  {
  const newLocations = fromJS(action.locations).filter((newItem) => (
    !state.get('stores').find((oldItem) => (
      oldItem.location.name === newItem.location.name
    )
  );

  return state.set('stores', state.get('stores').update(newLocations));
}

Upvotes: 1

Related Questions