我今天早些时候问过类似的问题,但这个问题的输出是不同的。我第一次问错了:(
我有一个大数组,为了问题目的我对其进行了简化
[
{"item1": 3, "item40": 2},
{"item1": 4, "item40": 8}
]
我想最终得到这个,它是对象数组中每个相似属性的总和。我尝试了很多。在里面做一个 forEach 和一个 forIn 。但我被困住了。请帮忙:)
[7, 10]
let arr = [
{"item1": 3, "item40": 2},
{"item1": 4, "item40": 8}
]
const res = Object.keys(arr[0]).map(key => arr.reduce((acc, cur) => acc + parseInt(cur[key] || 0), 0))
console.log(res)
您首先需要获取所有数据项的一组键,因为每个键的顺序和外观可能与数据数组中的每个项不同。
然后您可以将键映射到所有项目的减少。
const data = [ { "item1": 3, "item40": 2 }, { "item1": 4, "item40": 8 } ];
const keys = [...new Set(data.reduce((keys, obj) =>
[...keys, ...Object.keys(obj)], []))];
const summary = keys.map((key) =>
data.reduce((acc, item) => acc + (item[key] || 0), 0));
console.log(summary); // [ 7, 10 ]
最好保留键值对...
const data = [ { "item1": 3, "item40": 2 }, { "item1": 4, "item40": 8 } ];
const keys = [...new Set(data.reduce((keys, obj) =>
[...keys, ...Object.keys(obj)], []))];
const summary = keys.map((key) => ({
key,
value: data.reduce((acc, item) => acc + (item[key] || 0), 0)
}));
// [{"key": "item1", "value": 7}, {"key": "item40", "value": 10}]
console.log(summary);
更新 这是一个更好的版本。您减少了项目,并且对于每个项目,您都减少了键。
const data = [ { "item1": 3, "item40": 2 }, { "item1": 4, "item40": 8 } ];
const keys = [...new Set(data.reduce((keys, obj) =>
[...keys, ...Object.keys(obj)], []))];
const summary = data.reduce((values, item) =>
keys.reduce((acc, key) =>
({ ...acc, [key]: acc[key] + (item[key] || 0)})
, values
, {}));
console.log(summary); // { "item1": 7, "item40": 10 }
console.log(Object.values(summary)); // [ 7, 10 ]
如果您对外部模块开放,您可以使用
lodash
的 _.sumBy
很好地做到这一点:
const data = [
{ item1: 3, item2: 4, item40: 2 },
{ item1: 4, item2: 4, item40: 8 },
];
let output = {} // final result stored here
let keys = _.keys(data[0]) // or Object.keys(data[0]) // using the first object as a template to see what keys to search for
keys.forEach(key => output[key] = _.sumBy(data, key)) // sum them up
document.write(`<pre>${JSON.stringify(output, null, 4)}</pre>`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
过去
data[0]
的对象是否缺少键或有额外的键并不重要,但请注意,只有在data[0]
中找到的键才会被求和
这是一个使用
Map
来维护对象属性顺序的版本:
const data = [{
item1: 3,
item40: 2
},
{
item1: 4,
item40: 8
},
];
const arr =
// Array.from converts iterator from values() below to array
Array.from(
data
.reduce((map, obj) => {
// accumulate each object's values into map
Object.entries(obj).forEach(([propName, value]) => {
map.set(propName, (map.get(propName) ? ? 0) + value);
});
return map;
}, new Map())
// extract all values from map into an iterator
.values()
);
console.log(arr); // [ 7, 10 ]
const itemsArray = [
{ item1: 3, item2: 4, item40: 2 },
{ item1: 4, item2: 4, item40: 8 },
];
const sums = {};
for (const obj of itemsArray) {
for (const key in obj) {
if (!sums[key]) {
sums[key] = 0;
}
sums[key] += +obj[key] || 0;
}
}
const result = Object.values(sums);
console.log(result); // Output: [7, 10]