最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sum all properties of objects in array - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Dec 3, 2016 at 7:33 hszhsz 152k62 gold badges267 silver badges320 bronze badges 2
  • 2 Low quality question from a user of very high reputation. Disappointed -_- – Mulan Commented Dec 3, 2016 at 10:24
  • @naomik Don't judge - every one has worst day. – hsz Commented Dec 3, 2016 at 12:57
Add a ment  | 

6 Answers 6

Reset to default 5

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./ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

Docs:

  • https://lodash./docs/4.17.2#mergeWith,
  • https://lodash./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)

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

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

use _.mergeWith

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

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) 
)

bining 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
    })
})
发布评论

评论列表(0)

  1. 暂无评论