Reputation: 1904
I have one array logicalAddress which has 2 objects , now I have another object obj which has some value and I have to add in the array logicalAddress as new object or update the existing object . if orderNo is available in obj and its matching with any of the orderNo in array then it should update the complete object else it should add new obj. Please help . Getting confused .
logicalAddress
0:
orderNo: "AB1"
RelNo: "001"
denomination: "Testing"
lineNo: "09"
quantity: "4000"
1:
orderNo: "AB2"
RelNo: ""
denomination: "Testing"
lineNo: ""
quantity: "5000"
const obj ={
orderNo: "AB2"
RelNo: ""
denomination: "Testing"
lineNo: ""
quantity: "8000"
}
Upvotes: 0
Views: 184
Reputation: 1245
let logicalAddress = [
{
orderNo: 'AB1',
RelNo: '001',
denomination: 'Testing',
lineNo: '09',
quantity: '4000',
},
{
orderNo: 'AB2',
RelNo: '',
denomination: 'Testing',
lineNo: '',
quantity: '5000'
}
];
const obj = {
orderNo: 'AB2',
RelNo: '',
denomination: 'Testing',
lineNo: '',
quantity: '8000',
};
Find whether the record is presented or not in array. If yes then get the index of it using findIndex
and remove it and push else directly push it.
const objIndex = logicalAddress.findIndex(address => address.orderNo ===
obj.orderNo);
if(objIndex !== -1){
logicalAddress.splice(objIndex);
}
logicalAddress.push(obj);
console.log(logicalAddress);
Upvotes: 1
Reputation: 777
So you'll want to loop through each item the logicalAddress array and compare it with your object. Like you say, for the comparison we want to look for whether orderNo exists and if it matches any orderNo in the array. Assuming you are using ES6 that might look something like.
const logicalAddress = [
{
orderNo: 'AB1',
RelNo: '001',
denomination: 'Testing',
lineNo: '09',
quantity: '4000',
},
{
orderNo: 'AB2',
RelNo: '',
denomination: 'Testing',
lineNo: '',
quantity: '5000',
},
];
const obj = {
orderNo: 'AB2',
RelNo: '',
denomination: 'Testing',
lineNo: '',
quantity: '8000',
};
let objMatch = false;
if (obj.orderNo) { // If we have an order number
logicalAddress.forEach((address, i) => { // Loop array
if (address.orderNo === obj.orderNo) { // If address and obj numbers match
// Update value
logicalAddress[i] = obj;
objMatch = true;
}
});
}
if (!objMatch) { // If after looping through we have no match
logicalAddress.push(obj); // Add obj to array
}
Upvotes: 1