Skip to content

Instantly share code, notes, and snippets.

@chocopuff2020
Last active January 4, 2018 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chocopuff2020/380d67f5828d1f30e2822a885b886abc to your computer and use it in GitHub Desktop.
Save chocopuff2020/380d67f5828d1f30e2822a885b886abc to your computer and use it in GitHub Desktop.
getIn()-Michelle
var m = {
  username: "Sally",
  profile: {
    name: "Sally Clourian",
    address: {
      city: "Austin",
      state: "TX"
    }
  }
};

Solution 1: FOR loop

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

Solution 2: Recursive

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment