I have a deeply nested object
const myObject = {
a: {
b: {
c: [
{
t: {finallyHere: 'no!'}
},
{
d: {finallyHere: 'yes!'}
},
]
}
}
}
my output object would look like, output = [a, b, c, 1, d]
the function I will pass is getPath(myObject, 'd')
function I am trying so far,
function getPath(obj, key) {
paths = []
function getPaths(obj, path) {
if (obj instanceof Object && !(obj instanceof Array)) {
for (var k in obj){
paths.push(path + "." + k)
getPaths(obj[k], path + "." + k)
}
}
}
getPaths(obj, "")
return paths.map(function(p) {
return p.slice(p.lastIndexOf(".") + 1) == key ? p.slice(1) : ''
}).sort(function(a, b) {return b.split(".").length - a.split(".").length;})[0];
}
for which I am getting undefined, please help with the output