I have a nested object as follows, and I want to find out the key name if value is given to me.
const a = {
"key1": 12,
"key2": {
"nkey1": 123,
"nkey2": 345
}
};
const temp = (obj, val) => {
return Object.keys(obj).find(key => !(typeof obj[key] === "object") ? obj[key] === val : temp(obj[key], val))
}
console.log(temp(a, 345));
I wrote the above piece of code. But it gives me output as key2 whereas I want output as nkey2.
What am I doing wrong?
typeof obj[key] === "object" ? obj[key] === val : temp(obj[key], val)- Ifobj[key]is an object, strictly-compare this object withvalotherwise calltemp(obj[key], val). You might want to re-think the order of operations... ;)