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

时间:2018-12-15 12:50:30

标签: reactjs react-native react-redux react-native-ios react-native-flatlist

我在我的React Native App中编写了一个函数,我已经调用了一个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>
);

2 个答案:

答案 0 :(得分:1)

您几乎可以纠正逻辑,

这可以是实现此目标的一种方式,

 let everyOneObj = { name:'Everyone', income: 0, spending: 0 };

 itemList.forEach((item) => { `
      everyOneObj.income += item.income;
      everyOneObj.spending += item.spending;
 });

 itemList.push(everyOneObj);

答案 1 :(得分:0)

您需要使用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 }
]