var m = {
username: "Sally",
profile: {
name: "Sally Clourian",
address: {
city: "Austin",
state: "TX"
}
}
};
function getIn(obj, path, notFound = null) {
for (let i = 0; i < path.length; i++) {
var currentKey = path[i];
var currentValue = obj[currentKey];
if (obj[currentKey] === undefined) {
return notFound;
} else {
obj = currentValue;
}
}
return currentValue;
}
getIn(m, ["profile", "address", "city"]); // Austin
getIn(m, ["profile", "phone", "city"]); // null
getIn(m, ["profile", "name"]); //Sally Clourian
function getIn(obj, path, notFound = null) {
var count = 0;
let result= "";
var keyObj = obj[path[count]];
(typeof keyObj === "object") ? getIn(keyObj, path.slice(count+1)) : (keyObj === undefined) ? console.log(notFound) : console.log(keyObj);
}
getIn(m, ["profile", "address", "city"]); // Austin
getIn(m, ["profile", "phone", "city"]); // null
getIn(m, ["profile", "name"]); //Sally Clourian