1

I am new to javascript and I want to loop through json data and add accumulative number to the end of it. Here is a sample dataset:

[{'a':123,'b':345,'c':{'b1':1,'b2':2,'b3':3}},  
 {'a':234,'b':456,'c':{'b1':2,'b2':4,'b3':6}},  
 {'a':345,'b':567,'c':{'b1':3,'b2':6,'b3':9}}]  

And this is what I want to achieve:

[{'a':123,'b':345,'c':{'b1':1,'b2':2,'b3':3},'d':345+1+2+3},  
 {'a':234,'b':456,'c':{'b1':2,'b2':4,'b3':6},'d':456+2+4+6},  
 {'a':345,'b':567,'c':{'b1':3,'b2':6,'b3':9},'d':567+3+6+9}]  
1
  • 1
    Did you try a forEach() function? Commented Sep 29, 2018 at 19:30

1 Answer 1

2

Use Array.map() to iterate the array, and generate new objects that contain the property d. For each object in the array, use destructuring with rest to assign a value to a property, and the rest of the properties to an object (named rest in this case).

Create a new object, using a and rest (by spreading it), and add the d property, which is the sum of all rest properties.

To sum object properties recursively I've added the sumProps method. The function uses Object.values() to get an array of values. Then it iterates an sum them using Array.reduce(). Unless a value is an object, in which case we run it through sumProps again.

const data = [
 {'a':123,'b':345,'c':{'b1':1,'b2':2,'b3':3}},
 {'a':234,'b':456,'c':{'b1':2,'b2':4,'b3':6}},
 {'a':345,'b':567,'c':{'b1':3,'b2':6,'b3':9}}
];

const sumProps = (o) =>
  Object.values(o) // get the values of an object
    .reduce((r, v) => // iterate the values
      r + (typeof v === 'object' ? sumProps(v) : v) // add the values to the previous sum, and if the values are an object sum it recursively
    , 0);

// iterate the objects with map
const result = data.map(({ a, ...rest }) => { // destructure a, and an object of all other params
  return ({ // combine them back to an object
    a,
    ...rest, // spread the rest object
    d: sumProps(rest) // get the sum of the rest, and assign to d
  });
});

console.log(result);

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the prompt response, but because I am really new to the js, i have no idea what does the code mean, for example: const sumProps = (o) => Object.values(o) .reduce((r, v) => r + (typeof v === 'object' ? sumProps(v) : v) , 0); Can you please explain to me what does it do or maybe some reference to it? Thank you so mucj!
I've included an explanation and links to mdn articles about the method used. Enjoy :)
You are the best! :)
Elegant answer @Ori Drori

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.