I am pushing row dynamically on add new button click in my form. The new data will be added in oldData array in the form of object.
I want to match all values of newData object with oldData array, if newData object with same values is available in oldData array of objects, Then code will console error else it push the row.
const oldData = [{"productType":"Laundry","processTechType":"Continuous","subfamilyId":["TR - Flexibles"],"lineId":["R_X001_NGFCL14_01"],"batchSize":"NA"},{"productType":"Water Purification","processTechType":"Batch-Crunch","subfamilyId":["TR - Flexibles"],"lineId":["R_X001_NGFCL13_02"],"batchSize":"5"}];
const newData = {"productType":"Water Purification","processTechType":"Batch-Crunch","subfamilyId":["TR - Flexibles"],"lineId":["R_X001_NGFCL13_02"],"batchSize":"5"};
Below is my code
addNewType(rowdata) {
const newData = rowdata.value;
const oldData = this.items.value;
for (const item of oldData) {
let sameMakeProcessTypeId = 0;
if (item.productType === newData.productType && item.processTechType === newData.processTechType && item.batchSize === newData.batchSize) {
sameMakeProcessTypeId = 1;
console.log(sameMakeProcessTypeId,"sameMakeProcessTypeId");
if (sameMakeProcessTypeId > 1) {
console.log('This element already exists in the detail list');
} else if (sameMakeProcessTypeId > 1) { {
this.addItem(this.createItem(null));
}
}
}
}
Can anyone please help me to make my function working.
CodePudding user response:
I do it like this:
private allElementExists(newData: any[], oldData: any[]): boolean {
for (const item of newData) {
var verifyItem = oldData.find(x => x.id === item.id);
if (verifyItem === undefined) {
return false;
}
}
return true;
}
Here you have a function that compares the two objets as you putted in your question
Here is an example in stackblitz using this function
https://stackblitz.com/edit/angular-xscnkf?file=src/app/app.component.html
CodePudding user response:
If oldData keeps several objects, you can do:
if(!oldData.includes(newData))
EDIT 1 (for original code in description): if both are just single objects, simple comparison will do:
if(oldData! = newData)
EDIT 2 (for edited code in description):
addNewType(rowdata) {
const newData = JSON.stringify(rowdata.value);
const oldData = JSON.stringify(this.items.value);
if(oldData.includes(newData)){
console.log('This element already exists in the detail list');
}
else this.addItem(this.createItem(null));
}