0

Lets say i have an array with objects like this;

let employees = [{Name: 'Misha', Age: 25}, {Name: 'Karing', Age: 26}, {Name: 'Stephan', Age: 24}]

And i need to find some item in this object and change it's value. In order to find value i can use filter

events.filter(e => (e.Age === 25));

Should it be like this ?

events.filter(e => (e.Age === 25)).Age= 26;

But have do modify this value then? Let say i found someone who is 25 and i need to increase age to 26 ?

Vlad
  • 419
  • 1
  • 10
  • 21
  • do you look only for one object or could you get more? – Nina Scholz Feb 02 '22 at 18:12
  • *"Should it be like this ?"* No, because `filter` returns an array, and arrays don't have an `Age` property. You're looking for `find`, see the linked question's answers, or just a loop if you want to change the property on multiple elements (since you seem to be changing the value in place, not making a copy as you might in functional programming or when dealing with an immutable state object -- if you were doing that, you'd probably use `map` to get a new array with [when necessary] new objects). – T.J. Crowder Feb 02 '22 at 18:12
  • So basically: `events.find(({Age}) => Age === 25)?.Age = 26;` or (if you wanted to use the property value during the update) `const event = events.find(({Age}) => Age >= 25); ++event.Age;` (I changed the condition since otherwise we'd know it was 26). – T.J. Crowder Feb 02 '22 at 18:15

1 Answers1

0

You could map your array and change values on the fly. Here's one way of approaching it.

let employees = [{Name: 'Misha', Age: 25}, {Name: 'Karing', Age: 26}, {Name: 'Stephan', Age: 24}]
let changeAge = (from, to) => employees = employees.map(e => (e.Age === from ? {...e, Age: to} : e));

changeAge(25, 26);
console.log(employees)
Kinglish
  • 23,358
  • 3
  • 22
  • 43