简体   繁体   中英

How to map through an array of objects and add value to each other in React?

I would like to sum one specific value from my array of objects.

my array:

const myArray = [
{package_id: 1, width: "30"},
{package_id: 2, width: "20"},
{package_id: 3, width: "50"}
]

The value I would like to achive is the width. So the result would be 100 Is there any way to do this?

You can do it easily with a reduce function.

yourArray.reduce((acc, curr) => {
  return acc + parseInt(curr.width, 10);
}, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM