Use recursion to find the key/values of all objects nested or otherwise:
function finder(obj) {
// for each property in the object passed into
// the function...
for (var p in obj) {
// if its value is another object (see appended note)...
if (Object.prototype.toString.call(obj[p]).slice(8, -1) === 'Object') {
// ...log the key to the console and then call finder()
// again with this current object (this is the recursive part)
console.log('key: ' + p + ', value: Object');
finder(obj[p]);
// otherwise log the key/value
} else {
console.log('key: ' + p + ', value: ', obj[p]);
}
}
}
finder(x);
OUTPUT
key: 40, value: Object
key: length, value: 2
key: data, value: Array [ "11", "22" ]
key: 41, value: Object
key: length, value: 1
key: data, value: Array [ "fe" ]
key: 42, value: Object
key: length, value: 2
key: data, value: Array [ "ef", "ab" ]
NOTE
This rather long-winded line of code to check if a value is an object
Object.prototype.toString.call(obj[p]).slice(8, -1) === 'Object'
is necessary because typeof obj[p] === 'object'
will return true
for arrays and null
too. It's a bit of a gotcha.
Object.prototype.toString.call({})
returns a string like "[object Object]"
, and the slice
grabs the relevant section of the string.