简体   繁体   English

如何在反应本机中使用新对象更新数组对象

[英]how to update object of array with new object in react native

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 .我有一个包含 2 个对象的数组 logicalAddress,现在我有另一个具有某些值的对象 obj,我必须将数组 logicalAddress 添加为新对象或更新现有对象。 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.如果 obj 中的 orderNo 可用并且它与数组中的任何 orderNo 匹配,那么它应该更新完整的对象,否则它应该添加新的 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"

}

So you'll want to loop through each item the logicalAddress array and compare it with your object.因此,您将需要遍历 logicalAddress 数组中的每个项目并将其与您的对象进行比较。 Like you say, for the comparison we want to look for whether orderNo exists and if it matches any orderNo in the array.就像您说的,为了进行比较,我们要查找 orderNo 是否存在以及它是否与数组中的任何 orderNo 匹配。 Assuming you are using ES6 that might look something like.假设您使用的 ES6 可能看起来像。

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
}
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.如果是,则使用findIndex获取它的索引并删除它并推送 else 直接推送它。

const objIndex = logicalAddress.findIndex(address => address.orderNo === 
obj.orderNo);

if(objIndex !== -1){
  logicalAddress.splice(objIndex);
 }

 logicalAddress.push(obj);

 console.log(logicalAddress);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM