Skip to content Skip to sidebar Skip to footer

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 obj

Solution 1:

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 },
];

constincrement = a => a + 1;

const result = data.map(o => ({ ...o, foo: increment(o.foo) }));
console.log(result);

Solution 2:

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
}];

constincrement = a => a + 1;

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

console.log(result);

Solution 3:

For a in situ version, you could use a closure over the key of the object and take the object as parameter.

const data = [{ foo: 1, bar: 2 }, { foo: 2, bar: 3 }, { foo: 3, bar: 4 }];
constincrement = k => o => o[k]++;

data.forEach(increment('foo'));
console.log(data);

Solution 4:

what about:

data.map(d => (
  Object.assign({}, d, {foo: d.foo + 1})
));

Solution 5:

Isn't all this completely equivalent to just:

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

const result = data.slice();
result.forEach(e => e.foo++);
console.log(result);

Post a Comment for "Iterate Over Array Of Objects And Change One Property In Each Object"