Reputation: 116
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.
Upvotes: 0
Views: 46
Reputation: 350760
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));
Upvotes: 1
Reputation: 9873
Here is a simple scenario you might follow:
Object.keys(...)
on the root objectYou 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! :)
Upvotes: 0