我正在尝试获取每个数组在其各自对象中的总长度计数...
campus : {
"mchale": {
"classes":["ESJ030", "SCI339"], // get the length
"faculty":["Hardy", "Vikrum"] // get the length
},
"lawerence":{
"classes":["ENG001"], // get the length
"faculty":["Speedman", "Lee", "Lazenhower"] // get the length
}
}
这是我的:
const arrCount = campus.mchale.classes.length + campus.mchale.faculty.length + campus.lawerence.classes.length ...
是否有更好/更漂亮的方法来检索对象中存在的每个数组的总数?
最佳答案
您可以使用 Object.keys
与 map
和 reduce
收集数组,获取它们的长度,然后对这些值求和:
const data = {
"mchale": {
"classes":["ESJ030", "SCI339"], // get the length
"faculty":["Hardy", "Vikrum"] // get the length
},
"lawerence":{
"classes":["ENG001"], // get the length
"faculty":["Speedman", "Lee", "Lazenhower"] // get the length
}
};
const count = Object.keys(data).map(campusName => {
const campus = data[campusName];
return Object.keys(campus).map(key => campus[key].length).reduce((p, c) => p + c, 0);
}).reduce((p, c) => p + c, 0);
console.log(count);
关于javascript - 获取对象 ES6 中数组的总数/长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37349773/