How do you add up 2 numbers from a duplicate JSON key?

I have to display data from the JSON file we got.

There are a few entries that have a duplicate object. You can see it here :

2 categories called “fruit” which each have a different number. However, The way my code currently is set up doesn’t seem to add-up both numbers and showcase it as one.

It results in the following sight :

As you can see, the numbers on “Ma” and “Wo” overlap. Also, the values are set to the very first value they find. No idea what happened on the “Zo” rectangle-display, but yeah.

My code is the following :

 for (i = 0; i < beterData.results.length; i++) {
        var dagen = beterData.results[i]; 
        text("Gegeten fruit", width / 3 + 50, 150);

            text(dagenAfkorting[i], 165 + i * 95, 500)

            // loopen door activiteiten per individuele dag
            for (j = 0; j < dagen.activity.length; j++) {

                var fruit = dagen.activity[j];

                //de fruit string zoeken in de categorie-sectie

                if (fruit.category == "fruit") {

                    if (fruit.quantity < dagen.goals[j].quantity) {
                        fill(255, 0, 0);
                    } else {
                        fill(0, 255, 0);

                    rect(165 + i * 95, 480, 30, -fruit.quantity * 25);
                    text(fruit.quantity, 100 + i * 70, 200);

How can I add-up the duplicate “fruit” strings to 1 number and showcase it on screen?

Important EDIT: I am not allowed to change anything in the JSON-file

1 Like

From your picture, I can see your have the field activity which is an array. You should be able to iterate through every element of this JSONarray and check for the category and if it is the same, then you add them up.


Thanks for the comment,

I am aware of this, however i seem to be unable to do it. I have been stuck on this for a few days now

You can use a function like this to merge the objects in each activity array:

function mergeActivity(activity) {
	const output = [];
	for (const item of activity) {
		const filteredArr = output.filter(a => a.category === item.category);
		const index = output.indexOf(filteredArr[0]);
		output[index].quantity = output[index].quantity + item.quantity;
	return output;

Before you do any other code (but after reading in the json), you would use it like this:

const beterData = howeverYouGetTheData();
for (let i = 0; i < beterData.results.length; i++) {
	beterData.results[i].activity = mergeActivity(beterData.results[i].activity);

And then below there, all the activities will be merged for all the results in beterData and you can use it as normal.