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);
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!
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.
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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With