I have an object and I want to build up a function, take the object and a property name and the function returns the value of that property, if you see that you gonna say, "Oh it's so easy, just use a double quotation or dot notation to access that value" BUT I want the function to return me not only the first level property value, But also their nested if there's any object inside that object and search for that propertyName if exists accumulate the value in the array, and return the result:
let obj = {
a: {
b: "value of b",
},
b: "another value of b",
c: {
d: [1, 2, 3],
},
};
// input output
getDeepValuesProperty(obj, "a"); //{ b: "value of b" }
getDeepValuesProperty(obj, "b"); //["value of b", "another value of b"]
getDeepValuesProperty(obj, "d"); //[1, 2, 3]
let obj = {
a: {
b: "value of b",
},
b: "another value of b",
c: {
d: [1, 2, 3],
},
};
function getDeepValuesProperty(object, propertyName) {
if (object[propertyName]) {
return object[propertyName];
} else if (typeof object[propertyName] == "object") {
return getDeepValuesProperty(object[propertyName], propertyName);
}
}
console.log(getDeepValuesProperty(obj, "a")); //{ b: "value of b" }
console.log(getDeepValuesProperty(obj, "b")); //another value of b
console.log(getDeepValuesProperty(obj, "d")); //undefined
The first example worked, but the second doesn't work as I expect and return just the last value, the third example return undefined
I don't know why this happens, do I miss anything in the recursion function?