迭代对象数组并更改每个对象中的一个属性 [英] Iterate over array of objects and change one property in each object
本文介绍了迭代对象数组并更改每个对象中的一个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我发现自己有很多这种模式。我有一个从api返回的对象数组,我需要操作所有对象中的一个属性。
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.
有没有办法使用ES6 / Babel或Typescript让这种模式更具说明性?
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);
推荐答案
对象传播( ...
),使用第3阶段在Babel中提供诀窍:
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);
这篇关于迭代对象数组并更改每个对象中的一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文