I have a nested object with different types of properties including string, object and array. 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. 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. You could use a recursive countKeys(t) and do a type analysis on t's type -
v in Object.values(t), reduce and count one plus the recursive result, countKeys(v)v in t, sum countKeys(v)t is neither an Object nor an Array, return zerofunction 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))