假设有一个由两个或多个对象组成的数组:
const arr =[{PM1:10, PM10:20},{PM1:20, PM10:30, CO:27}, {NO2:30}]
如何有效地计算组成数组的对象中每个属性的平均值?
我事先不知道每个对象的属性,即使有共同的属性。
我期望一个结果:
{PM1:15, PM10:25, CO:27, NO2:30}
我想我可以使用reduce,但我不知道如何使用。
您可以使用以下任一方法循环访问对象的属性名称for-in
(其中包括继承的属性)或来自的数组Object.keys
(事实并非如此)。在这两种情况下,仅可枚举的属性都包括在内。
例如:
const arr =[{PM1:10, PM10:20},{PM1:20, PM10:30, CO:27}, {NO2:30}];
const result = {};
const counts = new Map();
for (const element of arr) {
for (const key in element) {
if (Object.hasOwn(element, key)) {
// Count this property
counts.set(key, (counts.get(key) ?? 0) + 1);
// Add it to the sum
result[key] = (result[key] ?? 0) + element[key];
}
}
}
// Update with the averages
for (const [key, count] of counts) {
result[key] = result[key] / counts.get(key);
}
实例:
// Quick-and-dirty polyfill for older environments without `Object.hasOwn`:
if (!Object.hasOwn) {
Object.defineProperty(Object, "hasOwn", {
value: Function.prototype.call.bind(Object.prototype.hasOwnProperty),
writable: true,
configurable: true,
});
}
const arr =[{PM1:10, PM10:20},{PM1:20, PM10:30, CO:27}, {NO2:30}];
const result = {};
const counts = new Map();
for (const element of arr) {
for (const key in element) {
if (Object.hasOwn(element, key)) {
// Count this property
counts.set(key, (counts.get(key) ?? 0) + 1);
// Add it to the sum
result[key] = (result[key] ?? 0) + element[key];
}
}
}
// Update with the averages
for (const [key, count] of counts) {
result[key] = result[key] / counts.get(key);
}
console.log(result);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)