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

时间:2016-05-20 14:47:21

标签: 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 ...

有没有更好/更漂亮的方法来检索对象中每个数组的总数?

3 个答案:

答案 0 :(得分:3)

您可以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);

答案 1 :(得分:2)

您可以递归遍历对象键并对所有长度的数组对象求和:

var campus = {
    "mchale": {
        "classes":["ESJ030", "SCI339"],
        "faculty":["Hardy", "Vikrum"]
     },
    "lawerence":{
        "classes":["ENG001"],
        "faculty":["Speedman", "Lee", "Lazenhower"]
     }
};

function totalArrayLength(obj) {
    return Object.keys(obj).reduce((total, key) => {
        if (Array.isArray(obj[key])) {
            total += obj[key].length;
        } else if (typeof obj[key] === 'object') {
            total += totalArrayLength(obj[key]);
        }
        return total;
    }, 0);
}

console.log(totalArrayLength(campus));

答案 2 :(得分:1)

您可以将Array#reduceObject.keys()一起使用,如下所示。

Object.keys(campus).reduce((a, b) => campus[b].classes.length +
    campus[b].faculty.length + a, 0);



var 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
    }
};

var length = Object.keys(campus).reduce((a, b) => campus[b].classes.length + campus[b].faculty.length + a, 0);
console.log(length);