Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over array of objects and change one property in each object

I find myself presented with this pattern quite a bit. I have an array of objects that I get back from my api, and I need to manipulate just one of the properties in all of the objects.

Is there a way using ES6/Babel or Typescript to get that pattern to be a little more declarative?

Looking for some neat destructuring trick or something along those lines.

const data = [{ foo: 1, bar: 2}, 
              { foo: 2, bar: 3},
              { foo: 3, bar: 4}];

const increment = a => a + 1;

// Here is my typical pattern
const result = data.map(o => {
    o.foo = increment(o.foo);
    return o;
})

console.log(result);
like image 422
Richard.Davenport Avatar asked Feb 17 '17 20:02

Richard.Davenport


People also ask

How do you change one property in an array of objects?

To update an object's property in an array of objects, use the map() method to iterate over the array. On each iteration, check if the current object is the one to be updated. If it is, modify the object and return the result, otherwise return the object as is. Copied!

How do you iterate through an array of objects?

To iterate through an array of objects in JavaScript, you can use the forEach() method aong with the for...in loop. The outer forEach() loop is used to iterate through the objects array.

How do you change an object in an array?

To change the value of an object in an array:Use the Array. map() method to iterate over the array. Check if each object is the one to be updated. Use the spread syntax to update the value of the matching object.


2 Answers

Object spread (...), available in Babel using the Stage 3 preset, does the trick:

const data = [
  { foo: 1, bar: 2 }, 
  { foo: 2, bar: 3 },
  { foo: 3, bar: 4 },
];

const increment = a => a + 1;

const result = data.map(o => ({ ...o, foo: increment(o.foo) }));
console.log(result);
like image 143
Jordan Running Avatar answered Oct 09 '22 23:10

Jordan Running


This is a little more elegant I think - Object.assign is a good way to update an item in an object

const data = [{
  foo: 1,
  bar: 2
}, {
  foo: 2,
  bar: 3
}, {
  foo: 3,
  bar: 4
}];

const increment = a => a + 1;

// Here is my typical pattern
const result = data.map(o => Object.assign(o, {foo: increment(o.foo)}))

console.log(result);
like image 7
Simon H Avatar answered Oct 09 '22 22:10

Simon H