计算数组对象的嵌套对象中的底层元素

Count bottom-level elements in nested object of objects of arrays

我有一个“数组对象的对象”,我只需要获得“底层”数组中元素的总数 ...所以在这个例子中下面,我需要 return 19(计算元素 as):

var arr={ 'AA': { 'aa': ['a','b'],
                  'bb': ['c','d'],
                  'cc': ['e','f'],
                  'dd': ['g','h'] }, 
          'BB': { 'ee': ['i','j'],
                  'ff': ['k','l'] }, 
          'CC': { 'gg': ['m','n'],
                  'hh': ['o','p'],
                  'ii': ['q','r','s'] } };

我已经在用它了,但它并不漂亮:

var cnt=0;
for(var f0 in arr){
  for(var f1 in arr[f0]){
    cnt+=arr[f0][f1].length;
  }
}

可能最好使用 map and reduce but can't quite wrap my head around it. There are similar Q+A's (like ) 但我找不到适合这种情况的。

谢谢!

使用Object.values to access the values associated with each key, you can use a nested reduce统计所有底层元素:

var arr={ 'AA': { 'aa': ['a','b'],
                  'bb': ['c','d'],
                  'cc': ['e','f'],
                  'dd': ['g','h'] }, 
          'BB': { 'ee': ['i','j'],
                  'ff': ['k','l'] }, 
          'CC': { 'gg': ['m','n'],
                  'hh': ['o','p'],
                  'ii': ['q','r','s'] } };
                  
const cnt = Object.values(arr)
  .reduce((c, o) => c + Object.values(o)
    .reduce((c, a) => c + a.length,
            0),
          0);
  
console.log(cnt)