0

hi all i am using javascript working with array i have a set of data to do add array values object here i attached my code help how to solve this

data

var data=[{one:1,two:2},{one:1,two:2},{one:1,two:2},{one:1,two:2}]

expected output

var sumdata=[{one:4,two:8}]

NOTE:one two column name is not static

2 Answers 2

1
var resObj = {};
for (var i = 0; i < data.length; i++) {
   for (var item in data[i]) {
      if (!resObj.hasOwnProperty(item)) {
         resObj[item] = data[i][item];
      } else {
         resObj[item] += data[i][item];
      }
    }
 }
 var sumdata = [resObj];
Sign up to request clarification or add additional context in comments.

1 Comment

I think this is best answer
1

You could use an object as result and iterate the keys of the object and sum the values.

var data = [{ one: 1, two: 2 }, { one: 1, two: 2 }, { one: 1, two: 2 }, { one: 1, two: 2 }],
    result = data.reduce(function (r, o) {    // iterate array
        Object.keys(o).forEach(function (k) { // iterate the keys of the object
            r[k] = (r[k] || 0) + o[k];        // check if a property exists or take zero
        });                                   // and add the actual value
        return r;                             // return the object
    }, Object.create(null));                  // start with an empty object without
                                              // some prototypes 
console.log(result);

3 Comments

you'r technically modifying the same object here !
i would prob replace Object.create(null) with {}, but that's just me :) Nice answer !
it would not work, if you have toString as own property, an you like to count the values of it.

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.