Obretin Alexandru Obretin Alexandru - 6 months ago 9
Javascript Question

Find property without knowing where it is in the tree

Have a small question:

p: {
s: {
name: 'demo'
}
},
x: {
'something': 'me'
}
}


How do I get name without knowing exactly where it is in the object tree ?
Edit: How do I get to 'me' ?

Answer

You can iterate recursively:

function findByKeyName(obj, keyName) {
    for (var key in obj) {
        if (key === keyName) {
            return obj[key];
        } else {
            if (typeof obj[key] === "object" && obj[key] !== null) {
                return findByKeyName(obj[key], keyName);
            }
        }
    }
}

findByKeyName(obj, "name") //returns "demo"