5

I have the following:

const data = [
  { name: "Santa"
    age: 34
  },
  { name: "John"
    age: 23
  }
]

I should edit object elements through map().
For example: I want all age to be 68 and 46 relatively. (×2).

I tried to solve but I couldn't

data = data.map(e => {
      e.age *= 2;
});
2
  • Just in case it matters, your attempt was mutating source array and returned age properties only. So, more conventional use of map() would be something immutable, like that one. Commented Mar 30, 2020 at 17:54
  • 1
    for mutating approach, you may replace map() with forEach() and get your problem solved with more appropriate tool Commented Mar 30, 2020 at 17:56

7 Answers 7

4

You need use a return statement, also use let because your data is not in fact constant:

let data = [{
    name: "Santa",
    age: 34
  },
  {
    name: "John",
    age: 23
  }
]

data = data.map(e => {e.age *= 2; return e;});
console.log(data)

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

1 Comment

It sure does but OP asks for editing objects inside array, favoring mutation
1

The map function replaces the value in the array with the result returned by your lambda function (in your case your arrow function). Always make sure you return a value ;)

data = data.map(e => {
      return {..e, age: e.age * 2};
});

Comments

1

const data = [
  { name: "Santa", age: 34 },
  { name: "John", age: 23 }
];
console.log( data.map( item => ({
  ...item,
  age: item.age + 10 // modify here
})))
data.forEach( item => {
  item.age = item.age + 10 // modify direct object
})
console.log( data)

Comments

1

In your map() function, alter the age property of each object, then return the entire object:

const data = [
  { name: "Santa",
    age: 34
  },
  { name: "John",
    age: 23
  }
]

let resp = data.map(obj => {
      obj.age *= 2
      return obj
});

console.log(resp)

Comments

1

two small mistakes: 1) you need to place ',' after object values and you need a return

var data = [
  { name: "Santa",
    age: 34
  },
  { name: "John",
    age: 23
  }
]

 data.map(e=> {
      e.age *= 2;
});

console.log(data);

1 Comment

updated to include entire array with new values for age
1

Your logic will be correct if you return e;

data = data.map(e =>{e.age *= 2; return e})

let data = [
  { name: "Santa",
    age: 34
  },
  { name: "John",
    age: 23
  }
]

data = data.map(e =>{e.age *= 2; return e})
console.log(data);

Comments

0

Try with map

const data = [ { name: "Santa", age: 34 }, { name: "John", age: 23 }]
   
console.log(data.map(res=>({...res, age: res.age*2})))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.