Suppose I access a certain object that is inside an object, but I don't know what the key of the previous object is, is there any way to get the key of the parent of this object?
Basically I would like to get the relative node of a property of an object
var house = {
bedroom: {
bed: 'I am a bed'
}
}
I got I'm a bed
, I know her key is bed
but I don't know she is in bedroom
is there any way to get bedroom?
just by knowing bed
. It is similar to parentNode, but like in objects.
This is my wish: "bed.parentNode
result bedroom
" but in object;
One way you could do this is while you are iterating through the object, store the key as a variable.
function recurseObject(obj, parentNode) {
let result;
if (typeOf obj !== 'object') {
return
}
for(const key in obj) {
if(//house[key] is the element you want the parent node of) {
return parentNode
}
result = recurseObj(obj[key], key)
}
return result
}
This function simply recurses through an object passing it the previous key. When you find the value you want the parent node for you simple return it. If the logic in the if
block does not find what you want it will return undefined