Home > Software design >  change the value of object inside a list
change the value of object inside a list

Time:03-30

My code's output is like this:

let myArray = [{"num": "2", "name": "Jhon"}, {"num": "1", "name": "Sara"}, {"num": "2", "name": "Domnic"}, {"num": "3", "name": "Bravo"}]

How can I access value of num in each field of the list and if num: 2, change its value to 5?

CodePudding user response:

Use Array.forEach to change the original Array

let myArray = [{ "num": "2", "name": "Jhon" }, { "num": "1", "name": "Sara" }, { "num": "2", "name": "Domnic" }, { "num": "3", "name": "Bravo" }]
myArray.forEach((node) => node.num = node.num == "2" ? "5" : node.num);
console.log(myArray);

If you want to create a new array from the existing one, Use Array.map

let myArray = [{ "num": "2", "name": "Jhon" }, { "num": "1", "name": "Sara" }, { "num": "2", "name": "Domnic" }, { "num": "3", "name": "Bravo" }]
const newArray = myArray.map(({ ...node }) => node.num = node.num == "2" ? "5" : node.num);
console.log(newArray);

Please Note: Do not forget to use spread syntax ({ ...node }) else your original array will be modified here.

CodePudding user response:

You could use array map:

let myArray = [{
  "num": "2",
  "name": "Jhon"
}, {
  "num": "1",
  "name": "Sara"
}, {
  "num": "2",
  "name": "Domnic"
}, {
  "num": "3",
  "name": "Bravo"
}]

const result = myArray.map(({...item}) => {
  if (item.num == 2)
    item.num = "5"
  return item
})

console.log(result)

  • Related