Skip to content

Get nested property from an Object #28

Description

@niloy

Get nested property from an Object:

f(null, _) = null
f(a, []) = a
f(a, x:xs) = f(a[x], xs)
function getProp(obj, propStr) {
  const arr = propStr.split(".");

  function get(obj, propArr) {
    if (obj == null) {
      return null;
    } else if (propArr.length === 0) {
      return obj;
    } else {
      const head = propArr[0];
      const tail = propArr.slice(1);
      return get(obj[head], tail);
    }
  }

  return get(obj, arr);
}

// Usage:
const obj = {
  a: {
    b: 1
  }
};

console.log(getProp(obj, "a.b"));

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions