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);
what about:
This is a little more elegant I think - Object.assign is a good way to update an item in an object
Isn't all this completely equivalent to just:
Object spread (
...
), available in Babel using the Stage 3 preset, does the trick:For a in situ version, you could use a closure over the key of the object and take the object as parameter.