gpt4 book ai didi

javascript - 获取对象 ES6 中数组的总数/长度

转载 作者:行者123 更新时间:2023-11-30 07:57:02 24 4
gpt4 key购买 nike

我正在尝试获取每个数组在其各自对象中的总长度计数...

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.keysmapreduce收集数组,获取它们的长度,然后对这些值求和:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com