迭代对象数组并更改每个对象中的一个属性

Ric*_*ort 10 javascript ecmascript-6 spread-syntax

我发现自己有很多这种模式.我有一个从api返回的对象数组,我需要操作所有对象中的一个属性.

有没有办法使用ES6/Babel或Typescript来使该模式更具说明性?

寻找一些整齐的解构技巧或类似的东西.

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);
Run Code Online (Sandbox Code Playgroud)

Jor*_*ing 19

...使用Stage 3预设在Babel中提供的Object spread()可以解决问题:

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);
Run Code Online (Sandbox Code Playgroud)

  • @Hitmands OP特别要求提供与Babel一起使用的解决方案. (3认同)
  • @Hitmands是的.而这正是我的答案所展示的. (3认同)

Sim*_*n H 5

我认为这更优雅一些 - Object.assign 是更新对象中项目的好方法

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);
Run Code Online (Sandbox Code Playgroud)