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
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);
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];
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.