简体   繁体   English

通过for循环访问数组Object属性值

[英]Access the array Object property value through for loop

I want access the object property which in inside array how to access that through a for loop ex: 我想访问内部数组中的对象属性如何通过for循环访问它:

arr[{A:1},{A:2},{B:3},{C:3}] 

i want sum of each object. 我想要每个对象的总和。

If you have same known key in object, then you can try this 如果对象中有相同的已知键,则可以尝试此操作

var data = [{a:6},{a:8},{a:9}];
var dataLength = data.length;
var total = 0;
var i = 0;

while(i < dataLength){
total += data[i]["a"];
i++;
}

If you have object with unkown keys / dynamic keys, then use this, 如果你有未知键/动态键的对象,那么使用这个,

var data = [{a:6},{b:8},{c:9,e:5}];
var dataLength = data.length;
var total = 0;
var i = 0;

while(i < dataLength){

for(var propName in data) {
    if(data.hasOwnProperty(propName)) {
        var propValue = data[propName];
        total += propValue;
    }
}

i++;
}

 let arr = [{A:1},{A:2},{B:3},{C:3}] let sum = arr.reduce((ac, o) => ac + Object.values(o)[0], 0); console.log(sum); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM