Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update each element within array within single function

I have below array object –

[
{
 index:0,
 value:"Yes",
},
{
 index:1,
 value:"No",
},
{
 index:2,
 value:"No",
},
{
 index:3,
 value:"Yes",
},
]

I want to update value of each element in array with "NA"

I tried doing –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

obj.map(x=>{
x.value="NA"
});

This is not working.

>Solution :

You could use two ways

forEach, which would mutate the existing array

const obj = [
  {
    index: 0,
    value: "Yes",
  },
  {
    index: 1,
    value: "No",
  },
  {
    index: 2,
    value: "No",
  },
  {
    index: 3,
    value: "Yes",
  },
]

obj.forEach(x => {
  x.value = "NA"
})

console.log(obj)

map, which will return the new array

const obj = [
  {
    index: 0,
    value: "Yes",
  },
  {
    index: 1,
    value: "No",
  },
  {
    index: 2,
    value: "No",
  },
  {
    index: 3,
    value: "Yes",
  },
]

const newObj = obj.map(x => ({
  ...x,
  value: "NA",
}))

console.log(newObj)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading