Home > Software engineering >  How to modify items in an array of objects
How to modify items in an array of objects

Time:08-25

I have an array of objects as

const items = [
  {name: 'Sam', amount: '455gbjsdbf394545', role: 'admin'},
  {name: 'Jane', amount: 'iwhru84252nkjnsf', role: 'user'},
  {name: 'Alf', amount: '34hjbjbsdf94334', role: 'user'},

The amount in the array are encrypted. And i have a function decryptAmount() that receives amount and returns the decrypted value decryptAmount(amount)

In the end, I want a new array as

const items = [
  {name: 'Sam', amount: 101, role: 'admin'},
  {name: 'Jane', amount: 50, role: 'user'},
  {name: 'Alf', amount: 100, role: 'user'},
]

How do get my intended solution?

CodePudding user response:

Your best bet is to use the array map method. This method iterates over each array element and replaces it with the returned value.

let items = [...];
items = items.map(item => ({
   ...item,
   amount: decryptAmount(item.amount)
}));

Array Map on MDN:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

CodePudding user response:

You can run forEach loop

items.forEach(item => {
  item.amount = decryptAmount(item.amount);
});

This will modify every amount in the array

CodePudding user response:

You can try to iterate through your array and modify your objects So, you will have :

const items = [
  {name: 'Sam', amount: '455gbjsdbf394545', role: 'admin'},
  {name: 'Jane', amount: 'iwhru84252nkjnsf', role: 'user'},
  {name: 'Alf', amount: '34hjbjbsdf94334', role: 'user'}]

for(let i=0; i<items.length; i  ){
    items[i].amount = decryptAmount(items[i].amount);
}

That should edit the amount property of objects to the decrypted value

  • Related