简体   繁体   English

计算嵌套对象和 arrays 的键总数

[英]count the total number of keys from nested objects and arrays

I have a nested object with different types of properties including string, object and array.我有一个嵌套的 object 具有不同类型的属性,包括字符串、object 和数组。 I used the recursive approach to count the total number of keys (from key1 to key9) in the object, but failed to achieve the correct solution.我使用递归的方法来统计object中的key的总数(从key1到key9),但未能得到正确的解决方案。 Example of my code below.下面是我的代码示例。

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

I try to wrap my head around for many hours but couldn't get the solution.我试着绕了好几个小时,但找不到解决方案。 Can anyone explain me what I'm missing here and supposed to add to make it work?谁能解释一下我在这里缺少什么并应该添加以使其正常工作?

For the data provided, there are nine (9) keys.对于提供的数据,有九 (9) 个键。 You could use a recursive countKeys(t) and do a type analysis on t 's type -您可以使用递归countKeys(t)并对t的类型进行类型分析 -

  1. When it's an Object, for all v in Object.values(t) , reduce and count one plus the recursive result, countKeys(v)当它是 Object 时,对于Object.values(t)中的所有v ,减少并计数一加递归结果countKeys(v)
  2. When it's an Array, for all v in t , sum countKeys(v)当它是一个数组时,对于所有v in t ,求和countKeys(v)
  3. Otherwise t is neither an Object nor an Array, return zero否则t既不是 Object 也不是数组,返回零

 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM