Home > Blockchain >  How to search array of objects and prevent pushing new row if value is exist more than one Angular 8
How to search array of objects and prevent pushing new row if value is exist more than one Angular 8

Time:05-30

On click of AddMore button, I am pushing newData object into oldData, but before pushing I need to check below condition.

I want to check if productType, processTechType, familyMake and lineId columns values are exist more than once in oldData array, then it will throw error.

Below is my data:

const newData = {"processTypeId":0,"productType":"Savoury","processTechType":"Mustard","familyMake":["Jelly","Noodles"],"lineId":["R_X002_ACCESS","R_X002_BIB"],"batchSize":"4"}

const oldData = [
    {"processTypeId":0,"productType":"Savoury","processTechType":"Mustard","familyMake":["Jelly","Noodles"],"lineId":["R_X002_ACCESS","R_X002_BIB"],"batchSize":"1"},
    {"processTypeId":0,"productType":"Savoury","processTechType":"Mustard","familyMake":["Jelly","Noodles"],"lineId":["R_X002_ACCESS","R_X002_BIB"],"batchSize":"4"}
];

I did below code and it is perfectly working, but my code is comparing whole object with oldData array, but I want to check for only 4 column of newData object with oldData array.

Can anyone help me to do this.

addNewType(rowdata) {
    const newData = JSON.stringify(rowdata.value);
    const oldData = JSON.stringify(this.items.value);   
    if ((oldData.split(newData).length - 1) >= 2) {
     console.log("Item exist");
    } else {
      this.isRowExist = false;
      this.addItem(this.createItem(null));
    }
  }

CodePudding user response:

you can do it like this:

addNewType(newData) {
    let isDuplicate = false;
    for(let data of this.oldData){
        if(data.productType == newData.productType ||
           data.processTechType == newData.processTechType ||
           data.familyMake == newData.familyMake ||
           data.lineId == newData.lineId){
            isDuplicate = true;
            break;
        }
    }
    if(isDuplicate){
        // Do nothing
    }else{
        this.oldData.push(newData);
    }
}

CodePudding user response:

Using a find (*):

addNewType(newData) {
    const el=this.oldData.find(data=>
           data.productType == newData.productType ||
           data.processTechType == newData.processTechType ||
           data.familyMake.join('|') == newData.familyMake.join('|')) ||
           data.lineId == newData.lineId)
   if (!el)
   {
         this.oldData.push(newData)
   }
}

(*) See that using an "if" is like a "normal loop". The function return "undefined" if not find, so we use the comparison if (!el){...}

NOTE1: when we need compare two arrays we need compare the "value" of the arrays. This is the reason I use "join" -that return an string-, so I compare the two strings.

NOTE2: the comparison says that if one of the properties are equal. If you need that all the properties was equal use && instead ||

  • Related