Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
change the value of object inside a list

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!