1

I am writing a piece of function in my React Native App, I have called an api, and it turns me this json array with objects, and stored in this.props.data:

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

I wish to iterate throught this array object and sum up the income and spending value, eventually to generate out a new object (everyone) and appened to original this.props.data and make something looks like below:

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

My current attempt is below, but doesn't really work, please advise with code example, thanks

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 Answers 2

1

you have almost come near to correct logic,

this can be one way you achieve this,

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

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

 itemList.push(everyOneObj);
Sign up to request clarification or add additional context in comments.

Comments

0

You need to use reduce to create a single new object, not 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);

which prints

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.