0

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"

}

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

1
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);

1 Comment

I like this, very concise code. I tried to spell it out a lot more in my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.