计算嵌套对象和数组中键的总数

count the total number of keys from nested objects and arrays

我有一个嵌套对象,它具有不同类型的属性,包括字符串、对象和数组。我用递归的方法统计了对象中的key(从key1到key9)的总数,但是没有得到正确的解。下面是我的代码示例。

const data = {
  key1: '1',
  key2: '2',
  key3: { key4: '4' },
  key5: [
    {
      key6: '6',
      key7: '7',
    },
    {
      key8: '8',
      key9: '9',
    }
  ]
}

const countKeys = (data) => {
  let count = 0;

  const helper = (data) => {
    for (let value of Object.values(data)) {
      if (typeof value === 'object') {
        helper(value);
      }
      // this line is problematic as it counts each object in the array as key. 
      if (!Array.isArray(value)) count++;
    }
  }
  helper(data)
  return count;
}
console.log(countKeys(data)) // 10, correct answer is 9

我绞尽脑汁想了好几个小时,但还是找不到解决方案。任何人都可以向我解释我在这里缺少什么并应该添加以使其工作吗?

对于所提供的数据,有九 (9) 个键。您可以使用递归 countKeys(t) 并对 t 的类型进行类型分析 -

  1. 为Object时,对Object.values(t)中的所有v,归约加一递归结果,countKeys(v)
  2. 当它是数组时,对于t中的所有v,求和countKeys(v)
  3. 否则t既不是对象也不是数组,return零

function countKeys(t) {
  switch (t?.constructor) {
    case Object:                                     // 1
      return Object
        .values(t)
        .reduce((r, v) => r + 1 + countKeys(v), 0)
    case Array:                                      // 2
      return t
        .reduce((r, v) => r + countKeys(v), 0)
    default:                                         // 3
      return 0
  }
}

const data =
  {key1:"1",key2:"2",key3:{key4:"4"},key5:[{key6:"6",key7:"7"},{key8:"8",key9:"9"}]}

console.log(countKeys(data))