简体   繁体   中英

Sum an array in an array of objects

I have an array of objects with some car data inside:

const cars = [
{
"id": 1,
"car_make": "Lincoln",
"car_model": "Navigator",
"car_year": 2009,
"data": {
  "rating": 4.9,
  "engines": [3, 4, 5, 6]
}
},
{
"id": 2,
"car_make": "Mazda",
"car_model": "Miata MX-5",
"car_year": 2001,
"data": {
  "rating": 4.1,
  "engines": [1, 2]
}
},]

Next I need to sum all the engines numbers inside the data object in car: So I made the next function but everytime I try to console the array it remains unchanged.

cars.forEach(car => {
car.data.engines.reduce((a,b) => a+b,0)
})

console.log(cars);

You need to assign the reduce value to engines again

so change

car.data.engines.reduce((a,b) => a+b,0)

to

car.data.engines = car.data.engines.reduce((a,b) => a+b,0)

 const cars = [ { "id": 1, "car_make": "Lincoln", "car_model": "Navigator", "car_year": 2009, "data": { "rating": 4.9, "engines": [3, 4, 5, 6] } }, { "id": 2, "car_make": "Mazda", "car_model": "Miata MX-5", "car_year": 2001, "data": { "rating": 4.1, "engines": [1, 2] } }] cars.forEach(car => { car.data.engines = car.data.engines.reduce((a,b) => a+b,0) }) console.log(cars);

Basically the answer to the question should have been an map and create a new array from that old with the data changed.

const newCars = data.map(car => ({
id: car.id,
brand : car.car_make,
engineSum : car.data.engines.reduce((a,b) => a+b,0),
})).sort((a,b) => a.engineSum - b.engineSum);

console.log(newCars);

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