2016-12-03 60 views
0

我有以下數據集:總和數組對象的所有屬性

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

我需要總結所有的數組元素得到以下結果:

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

我不知道參數名稱所以我們不應該在任何地方痛。

什麼是最短將輸入數組中的所有對象合併(總和屬性)的方法?

有可能使用ES6功能和lodash。

+2

低質量的問題。失望-_- – naomik

+0

@naomik不要判斷 - 每個人都有糟糕的一天。 – hsz

回答

4

我想這是最短的可能的解決方案:

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>

文檔:

如果你是罰款的input的第一個元素被取代,則可以省略第一個參數:從非常高的聲譽用戶

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

使用Array#forEach方法與Object.keys方法。

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


隨着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

你可以遍歷鍵和總和。

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

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

1

使用_.mergeWith

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

是的,'mergeWith' - 但做得對(看上面) – georg

+0

@georg是的,你是對的,美麗的解決方案 – stasovlas

0

Object.keys結合forEach工作

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