我有以下數據集:總和數組對象的所有屬性
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。
我有以下數據集:總和數組對象的所有屬性
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。
我想這是最短的可能的解決方案:
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)
使用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);
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);
你可以遍歷鍵和總和。
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);
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)
)
與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
})
})
低質量的問題。失望-_- – naomik
@naomik不要判斷 - 每個人都有糟糕的一天。 – hsz