简体   繁体   中英

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:

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:

 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
  • 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. Try it out and let me know if you need any help! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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