Iterate over array of objects and change one property in each object
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);
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 }];
const increment = k => o => o[k]++;
data.forEach(increment('foo'));
console.log(data);
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);