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

标签 javascript arrays

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

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/

相关文章:

javascript - React 替换 CSS 中的特殊字符 `content`

javascript - 使用 Javascript - 如何单击没有 ID、值或名称的提交按钮

javascript - 任何人都知道如何在 CSS 中制作它以便响应?

javascript - 如何创建一个包含动态 Div 数组列表的数组

php - 在 php 中迭代数组,但在迭代期间添加到数组/从数组中删除

java - 如何构建一个数组并将其与另一个数组进行比较?

javascript - 仅当用户登录/本地存储存在时,如何授予对 Vue.js 中页面的访问权限?

python - 选择数组的每 n 个索引

c++ - 无法填充 C++ 数组,每个索引处只有最后一项

php - 使用我的数据库创建一个简单的数组