Mark Steggles
Mark Steggles

Reputation: 5563

ImmutableJs - compare objects but for one property

I am converting a shopping basket to an immutable structure.

Is there an easy way with immutablejs to see if an immutable object already exists within an immutable list EXCEPT for one object property 'quantity' which could be different? List example:

[{
  id: 1,
  name: 'fish and chips',
  modifiers: [
    {
      id: 'mod1',
      name: 'Extra chips'
    }
  ],
  quantity: 2
},{
  id: 2,
  name: 'burger and chips',
  modifiers: [
    {
      id: 'mod1',
      name: 'No salad'
    }
  ],
  quantity: 1
}]

Now, say I had another object to put in the list. But I want to check if this exact item with modifiers exists in the list already? I could just do list.findIndex(item => item === newItem) but because of the possible different quantity property then it wont work. Is there a way to === check apart from one property? Or any way to do this without having to loop through every property (aside from quantity) to see if they are the same?

Currently, I have an awful nested loop to go through every item and check every property to see if it is the same.

Upvotes: -1

Views: 391

Answers (1)

hazardous
hazardous

Reputation: 10837

Well this should work-

list.findIndex(item => item.delete("quantity").equals(newItem.delete("quantity"))

The equals method does deep value comparison. So once you delete the quantity, you are comparing all values that matter.

PS: please ignore code formatting, I am on SO app.

PPS: the above code is not optimal, you should compare a pre-trimmed newItem inside the arrow function instead of trimming it there.

Upvotes: 1

Related Questions