user1354934 user1354934 - 2 months ago 10
Javascript Question

javascript - comparing values in an array of objects with a response array of objects

I'm building a small app where you add up to 10 items into a "bag".

Once an item is added to a bag, it is added into a

bag []
. Each item has an
id
.

However, I get the items from an API call, so when I get items, I want to ensure that if I have already added an item to bag, it doesn't mess with the bag state.

Here's what I'm doing when I receive items from the API:

items.map(i => {
i.inBag: false
});


However, this will reset the
inBag
even if I've added an item into my bag. When an item is added into a bag, the
inBag
flips to true. But next time the API call is made, it will reset to
false
.

How can I ensure that when I receive something from the API, that I also check whether the
i.id
exists in an item in
bag[]
?

I'm afraid it will be too slow if I do it by comparing in each iteration, so I'm wondering if there is a better way.

Thanks

Answer

Try this;

If bag is not array of object

if(bag.indexOf(received_item_id)==-1)
{
    //write code to insert item into bag[]
}

If bag is array of object

if(JSON.stringify(bag).indexOf(JSON.stringify(object_getting_from_api))==-1)
{
    //write code to insert item into bag[]
}
Comments