React Native通过数组对象进行迭代,并计算总和值



我正在我的React Native应用程序中编写一段函数,我调用了一个api,它给我带来了这个带有对象的json数组,并存储在this.props.data:中

[{name:'Jhon', income:28, spending:20},
{name:'Anna', income:82, spending:50},
{name:'Peter', income:141, spending:70}
]

我希望遍历这个数组对象,并总结收入和支出值,最终生成一个新对象(每个人(,并调用原始this.props.data,使其看起来如下:

[{name:'Jhon', income:28, spending:20},
{name:'Anna', income:82, spending:50},
{name:'Peter', income:141, spending:70},
{name:'Everyone', income:251, spending:140}
]

我目前的尝试如下,但没有真正起作用,请提供代码示例,谢谢

const CustomListview = ({ itemList }) => (
var everyoneObject = {
name: 'everyone',
income: 0,
spending: 0
}
itemList.map(({name, income, spending}) => { 
everyoneObject = {
name: 'everyone',
income: income++,
spending: spending++
}
})
itemList.push(everyoneObject);
<View style={styles.container}>
<FlatList
data={itemList}
renderItem={({ item }) =>
<TillReportRow
name={item.name}
income={item.income}
spending={item.spending}
/>}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);

您几乎已经接近正确的逻辑,

这可能是实现这一目标的一种方法,

let everyOneObj = { name:'Everyone', income: 0, spending: 0 };
itemList.forEach((item) => { `
everyOneObj.income += item.income;
everyOneObj.spending += item.spending;
});
itemList.push(everyOneObj);

您需要使用reduce来创建单个新对象,而不是map

const itemList = [
{ name: "Jhon", income: 28, spending: 20 },
{ name: "Anna", income: 82, spending: 50 },
{ name: "Peter", income: 141, spending: 70 }
];
const everyone = itemList.reduce(
(acc, { income, spending }) => {
acc.income += income;
acc.spending += spending;
return acc;
},
{ name: "everyone", income: 0, spending: 0 }
);
itemList.push(everyone);
console.log(itemList);

它打印

[
{ name: "Jhon", income: 28, spending: 20 },
{ name: "Anna", income: 82, spending: 50 },
{ name: "Peter", income: 141, spending: 70 },
{ name: "everyone", income: 251, spending: 140 }
]

相关内容

  • 没有找到相关文章

最新更新