Sum all properties of objects in array

2019-09-12 05:59发布

问题:

I have following dataset:

const input = [
  { x: 1, y: 3 },
  { y: 2, f: 7 },
  { x: 2, z: 4 }
];

I need to sum all the array elements to get following result:

const output = { f: 7, x: 3, y: 5, z: 4 };

I don't know the parameters names so we should not sore it anywhere.

What is the shortest way to merge (sum properties) all the objects from the input array into one ?

There is possibility to use ES6 features and lodash.

回答1:

I guess this is the shortest possible solution:

const input = [
  { x: 1, y: 3 },
  { y: 2, f: 7 },
  { x: 2, z: 4 }
];

let result = _.mergeWith({}, ...input, _.add);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

Docs:

  • https://lodash.com/docs/4.17.2#mergeWith,
  • https://lodash.com/docs/4.17.2#add

If you're fine with the first element of input being replaced, you can omit the first argument:

 _.mergeWith(...input, _.add)


回答2:

Use Array#forEach method with Object.keys method.

const input = [{
  x: 1,
  y: 3
}, {
  y: 2,
  f: 7
}, {
  x: 2,
  z: 4
}];

// object for result
var res = {};

// iterate over the input array
input.forEach(function(obj) {
  // get key from object and iterate
  Object.keys(obj).forEach(function(k) {
    // define or increment object property value
    res[k] = (res[k] || 0) + obj[k];
  })
})

console.log(res);


With ES6 arrow function

const input = [{
  x: 1,
  y: 3
}, {
  y: 2,
  f: 7
}, {
  x: 2,
  z: 4
}];

var res = {};

input.forEach(obj => Object.keys(obj).forEach(k => res[k] = (res[k] || 0) + obj[k]))

console.log(res);



回答3:

You could iterate the keys and sum.

var input = [{ x: 1, y: 3 }, { y: 2, f: 7 }, { x: 2, z: 4 }],
    sum = input.reduce((r, a) => (Object.keys(a).forEach(k => r[k] = (r[k] || 0) + a[k]), r), {});
console.log(sum);



回答4:

use _.mergeWith

_.reduce(input, function(result, item) {
    return _.mergeWith(result, item, function(resVal, itemVal) {
        return itemVal + (resVal || 0);
    });
}, {});


回答5:

const input = [
  { x: 1, y: 3 },
  { y: 2, f: 7 },
  { x: 2, z: 4 }
];

function sumProperties(input) {
  return input.reduce((acc, obj) => {
    Object.keys(obj).forEach((key) => {
      if (!acc[key]) {
        acc[key] = 0
      }
      acc[key] += obj[key]
    })
    return acc
  }, {})
}

console.log(
  sumProperties(input) 
)



回答6:

combining forEach with Object.keys works

const input = [
  { x: 1, y: 3 },
  { y: 2, f: 7 },
  { x: 2, z: 4 }
];

const output = { f: 7, x: 3, y: 5, z: 4 };

output = {}
input.forEach(function(obj){
    Object.keys(obj).forEach(function(key){
        output.key = output.key ? output.key + key || key
    })
})