Ad

How To Find Index Of An Array That Contains Specific Array In It?

- 1 answer

I'm developing a ecommerce cart, in the following cart each item could have some "variants", the item model looks like the following where Articoli == item and each Articoli could have an array of Varianti inside it:

class Articoli {
    constructor(id, titolo, qta, prezzo, prezzo_s, img, varianti) {
        this.id = id;
        this.titolo = titolo;
        this.qta = qta;
        this.prezzo = prezzo;
        this.prezzo_s = prezzo_s;
        this.img = img;
        this.varianti = varianti;
    }
}

class Varianti {
    constructor(id, titolo, stato, prezzo) {
        this.id = id;
        this.titolo = titolo;
        this.stato = stato;
        this.prezzo = prezzo;
    }
}

Now i have to update the quantity of each added item inside the Cart. Each added item if doesn't have any Variant has id cd-cart-ID while item with variant has id cd-cart-var-ID so when two items without any variants in it are added the quantity is just updated while if the same item is added with some variants in it it's created a new item in the cart but here comes the issue i could have items with same variants added so it's quantity has to be updated, but till now i was looking for array index that has equals ID so:

var objIndex = articoli.findIndex((obj => obj.id == id))

But the ID is equals in both added items like for an item cd-cart-ID the ID equals to 7891 and even in a new added item with variants with component ID cd-cart-var-ID ID equals to 7891 in the array.

So i was going to get the objectIndex to which update the quantity by checking it for ID and for Variants inside it like this:

var objIndex = articoli.findIndex((obj => obj.id == id && obj.varianti == articolo.varianti))

Where articolo.varianti is the array of objects Varianti, but it returns in any case index -1 even if i'm adding two items without any Variants so varianti == []...

Ad

Answer

It looks like your id or obj.varianti is undefined. You can use the folliwing example to find an index:

class Articoli {
  constructor(id, titolo, qta, prezzo, prezzo_s, img, varianti) {
      this.id = id;
      this.titolo = titolo;
      this.qta = qta;
      this.prezzo = prezzo;
      this.prezzo_s = prezzo_s;
      this.img = img;
      this.varianti = varianti;
  }
}


let articolies = [
  new Articoli(1, 'title 1', 'qta 1', 'prezzo1', 'prezzo_s 1', 'img 1', 'varianti 1'),
  new Articoli(1, 'title 111', 'qta 1', 'prezzo1', 'prezzo_s 1', 'img 1', 'varianti 111'),
  new Articoli(1, 'title 2', 'qta 2', 'prezzo2', 'prezzo_s 2', 'img 2', 'varianti 2')
]

let objToFind = new Articoli(1, 'title 111', 'qta 1', 'prezzo1', 'prezzo_s 1', 'img 1', 'varianti 111');
var objIndex = articolies.findIndex((obj => obj.id == objToFind.id && 
    obj.varianti == objToFind.varianti))

console.log(objIndex);

Ad
source: stackoverflow.com
Ad