I have the following javascript object
const reizen = { personen: [ { naam: "Bob", reizen: [ { locatie: "Frankrijk", uitgaven: [ { voorwerp: "Sokken", prijs: 15 }, { voorwerp: "Sleutelhanger", prijs: 6 }, { voorwerp: "Restaurant", prijs: 26 }, ] }, { locatie: "Duitsland", uitgaven: [ { voorwerp: "Taxi", prijs: 30 }, ] } ] }, ] }
I’m trying to get the sum of all values where it says ‘prijs’ (it’s in dutch) Is there an ‘easy’ way to do this?
EDIT: Thanks everyone for the amazing replies! I got it to work thanks to you guys.
Advertisement
Answer
Its not totally sexy – and I would not actually do this – but to give an alternative to the maps / reduces etc, especially if the object structure is variable or unknown – the simplest way to get the total count without recursion is to stringify the object (JSON.stringify), split on the “prijs’ to give an array of strings that start with the target numbers and then (ignoring the first item which does not contain any targert values), parseFloat the strings (which will parse the integer characters until the first non integer character) to get the numbers and add.
const reizen = { personen: [ { naam: "Bob", reizen: [ { locatie: "Frankrijk", uitgaven: [ { voorwerp: "Sokken", prijs: 15 }, { voorwerp: "Sleutelhanger", prijs: 6 }, { voorwerp: "Restaurant", prijs: 26 }, ] }, { locatie: "Duitsland", uitgaven: [ { voorwerp: "Taxi", prijs: 30 }, ] } ] }, ] } const stringifiedObj = JSON.stringify(reizen); const portions = stringifiedObj.split('prijs":'); let count = 0; for(let i = 1; i < portions.length; i++) { count += parseFloat(portions[i]) } console.log(count) // gives 77 (15 + 6 + 26 + 30)