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

核能气质少年 提交于 2019-12-18 20:49:33

问题


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);

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

const increment = a => a + 1;

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



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

const increment = a => a + 1;

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

console.log(result);



回答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 }];
const increment = k => o => o[k]++;

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



回答4:


what about:

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



回答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);


来源:https://stackoverflow.com/questions/42306471/iterate-over-array-of-objects-and-change-one-property-in-each-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!