简体   繁体   中英

Replace key value inside array of object with another object with same key

Suppose I have an array of object:

const purchaseDetails = [
  {
      amount: '4567',
      purchaseOrder: 'B234',
      purchaseDate: '10/12/2020',
      someRandom1: '123',
      someRandom2: '345'
   },
   {
      amount: '4567',
      purchaseOrder: 'B234',
      purchaseDate: '10/12/2020',
      someRandom1: '678',
      someRandom2: '987'
    }
]

and another object as:

const toReplace = {
      amount: '1211',
      purchaseOrder: 'A123',
      purchaseDate: '12/30/2020',
      vat: '123',
 }

I want to replace value of purchaseDetails with toReplace value

O/p as:

const purchaseDetails = [
    {
         amount: '1211',
         purchaseOrder: 'A123',
         purchaseDate: '12/30/2020',
         vat: '123',
         someRandom1: '123',
         someRandom2: '345'
     },
     {
         amount: '1211',
         purchaseOrder: 'A123',
         purchaseDate: '12/30/2020',
         vat: '123',
         someRandom1: '678',
         someRandom2: '987'
      }
  ]

For this i tried as:

purchaseDetails.forEach(element => {
  element.amount=toReplace.amount,element.purchaseOrder=toReplace.purchaseOrder,
   element.purchaseDate=toReplace.purchaseDate,element.tax=toReplace.tax
});

But it doesnot replace the value...i tried with single value as well but it's not working.

As per provided solution it was assignment issue.

But the second solution provided, when I try:

purchaseDetails.forEach(element => {
        element = {...element, ...avacado}
        console.log(element)
});

On console.log(element), it shows element with value changed but console.log(purchaseDetails) value doesnot change.

If you instead declare purchaseDetails via let (thus allowing reassigning the result of map call later), you can use Array.prototype.map :

 let purchaseDetails = [{ amount: '4567', purchaseOrder: 'B234', purchaseDate: '10/12/2020', someRandom1: '123', someRandom2: '345' }, { amount: '4567', purchaseOrder: 'B234', purchaseDate: '10/12/2020', someRandom1: '678', someRandom2: '987' } ] const toReplace = { amount: '1211', purchaseOrder: 'A123', purchaseDate: '12/30/2020', vat: '123', } purchaseDetails = purchaseDetails.map(obj => ({...obj, ...toReplace })); console.log(purchaseDetails);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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