0

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 -

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

This is not working.

1
  • 2
    You're not returning anything from the map callback. Try return x; after you've set the value. Note: map returns a new array. You may want forEach which can mutate the array instead - depends on your use-case. Commented Oct 13, 2022 at 11:12

3 Answers 3

1

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)

Sign up to request clarification or add additional context in comments.

3 Comments

can I assign it within same array ? (with map) .. Like - obj=obj.map(..
That's not how you should be using map. map transforms an array into a new array. @CSharper
@CSharper yes, you could, but you should not. Usually, map is used to create a new array based on the provided callback function (avoid mutation), while forEach is used only to execute the function on each element (mutation is okay)
1

There are two points need to pay attention:

  1. you need to assign the result to a new variable after using map
  2. inside the map function,we also need to return the mapped object via return

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

let result = data.map(d =>{
  d.value="NA"
  return d
})

console.log(result)

Comments

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

let arr= data.map(x =>{
  x.value="NA"
  return x
})

console.log(arr)

or with the old way

for(let i=0;i<data.lenght;i++){
data[i].value='na'
}
console.log(arr)

3 Comments

Small advice,before post answer,need to check others have posted the same or not
@lucumt Small advice,before post answer,need to check others have posted the same or not
Hey,why do you copy my comments, your answer is 4 minutes later posted than me and is the same with mine,so try to avoid the duplicate answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.