Gustavo Bocalandro
Gustavo Bocalandro

Reputation: 23

Item in array not recognized. - Js

I have an array of objects and I add new objects to it if the user make some choices. Then, when I refresh the page, I make sure I save these options, to keep showing them unless the user deletes them.

At the same time, if the user tries to add the same option once again, the code behind won´t let them do it.

The problem is that, after refreshing, if I try to add the same option again, the array does not recognize the existing item as the same as the one I try to add and it allows me to do so.

Actually, here is an example of an item and what I have in the array when that happens: item:

{name: "Vinos", type_products: "Vinos", active: true}
active: true
name: "Vinos"
type_products: "Vinos"
[[Prototype]]: Object

Array: filtersSelected.

this.filtersSelected[0]
{name: "Vinos", type_products: "Vinos", active: true}
active: true
name: "Vinos"
type_products: "Vinos"
[[Prototype]]: Object

So, as you see, it is the same thing, however, when I do any of these verifications, I always received the wrong value:

const index = this.filtersSelected.indexOf(item);    //the value is always -1
this.filtersSelected.filter(el => el == item)   //the value is always [] (an empty array)
this.filtersSelected.includes(item)   //the value is always false

How can I check / compare the values between what I have in the array and my item, to do some things, only, if the item is not already in the array?

(like

if(index <= -1){array.push(item);}

)

Thanks a lot!

Upvotes: 2

Views: 119

Answers (1)

dacodr
dacodr

Reputation: 167

You would have to determine which attribute(s) of those objects are the "key" that makes them unique and iterate the array looking for that key. When the key is not found, then add it to the array, otherwise, do nothing.

For example, if name + type_products represents the key you could do:

const myArrayOfProducts = [];

const addItemToMyProducts = (item) => {
  const { name, type_products } = item;
  const found = myArrayOfProducts.some(p => p.name === name && p.type_products === type_products);
  if (!found) {
    myArrayOfProducts.push(item);
  }
};

const item1 = {name: "Vinos", type_products: "Vinos", active: true};
const item2 = {name: "foo", type_products: "bar", active: true};
const item3 = {name: "Vinos", type_products: "Vinos", active: false};

addItemToMyProducts(item1); // Adds
addItemToMyProducts(item1); // Skips
addItemToMyProducts(item2); // Adds
addItemToMyProducts(item3); // Skips (key matches)

console.log(myArrayOfProducts);
// Returns 
// [
//   { name: 'Vinos', type_products: 'Vinos', active: true },
//   { name: 'foo', type_products: 'bar', active: true }
// ]

Upvotes: 2

Related Questions