0

I have an array that is at the beginning empty, so I have my function that I use to controll element inside array:

saveProducts(product){
 let originalProd = JSON.parse(localStorage.getItem("PRODUCT_ORIGINAL")) // at the beginning is null
  if( originalProd !== null && originalProd.length > 0){
  originalProd.some(element => {
    if ( element.productName !== product.name){
       this.originalProductToSave.push({ productName: product.name, productQuantity: product.quantity, productPrice: product.price })
    else if(element.productName === product.name && element.productQuantity !== product.quantity){ element.productQuantity = product.quantity}
     }
   }
 }
else{
  this.originalProductToSave.push({ productName: product.name, productQuantity: product.quantity, productPrice: product.price })
   }
}

Now this originalProductToSave is saved on localStorage in this way originalProd has the same values. My problem is about how to save elements inside array because I don't want duplicate, and using some I have duplicated inside, for example

originalProd=[{productName: "001",....}, {productName: "002",.....}]

So If I try for example to add another time product with name 002 it checks between 001 != 002 and it adds another time 002

Jack23
  • 1,368
  • 7
  • 32
  • You should refactor this method. SaveProduct, updateProduct, deleProd... etc. Instead of some I would use includes. – Beller Jan 26 '23 at 10:22

1 Answers1

1

So what you are looking for is adding an element to an array of objects on the condition that the array does not hold an object already which has the same value in its productName just like product.name , correct?

If so, there are multiple ways to solve this elegantly i think. For instance you could try JS' in-built find method (see here for docs) and try looking for an already existing entry like that:

// "deep checking" the objects for equality
let find = originalProd.find(elem =>
    elem.productName === product.name
    && elem.productQuantity === product.quantity
    && elem.productPrice === product.price);

if (!find) {
    // element is not contained yet, so add it
    // ...
}

Another elegant solution could be by just simply using a map instead of an array for storing your elements and using the in-built has method on maps (see here for docs).

Apart from that, you may find this related post helpful.

Hope this helps!

GringoFabi
  • 11
  • 2