简体   繁体   English

计算对象的所有属性

[英]Counting all properties of an object

I basically need to count the tags 'property1' and 'property2' such that the result comes out to be 4. The object looks somewhat like this: 我基本上需要对标签“ property1”和“ property2”进行计数,以使结果为4。该对象看起来像这样:

parent: {
  child: {
    child2: {
      child3: { property1: '', property2: '' }
    }
  },
  2child: {
    2child2: {
      2child3: { property1: '', property2: '' }
    }
  }
}

I need to count the specified properties but can't find a way to do so. 我需要计算指定的属性,但找不到解决方法。 The object can have many such child objects with their own child objects and all specified properties need to be counted. 该对象可以具有许多这样的子对象以及它们自己的子对象,并且需要计算所有指定的属性。 My first guess would be that recursion will be required. 我的第一个猜测是需要递归。

You can indeed use a recursive function. 您确实可以使用递归函数。 Also the methods Object.keys and Object.values will be useful: 同样, Object.keysObject.values方法将非常有用:

 function propCount(obj) { return Object(obj) !== obj ? 0 : Object.values(obj).map(propCount) .reduce( (a,b) => a+b, Object.keys(obj).length ); } var obj = {parent: {child: {child2: {child3: { property1: '', property2: '' }}},"2child": {"2child2": {"2child3": { property1: '', property2: '' }}}}}; console.log(propCount(obj)); 

Here is a simple scenario you might follow: 您可能会遵循以下简单方案:

  • Call Object.keys(...) on the root object 在根对象上调用Object.keys(...)
  • For each key, check if the value is another object. 对于每个键,请检查该值是否是另一个对象。 If so, recurse. 如果是这样,请递归。
  • If it's not an object, move on to the next key. 如果不是对象,请移至下一个键。
  • For each key, increment a counter. 对于每个键,增加一个计数器。

You can do all these steps in a small function with less than 10 lines of code. 您可以使用少于10行代码的小型函数来完成所有这些步骤。 Try it out and let me know if you need any help! 尝试一下,让我知道您是否需要任何帮助! :) :)

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

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