Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get nested property from an Object #28

Open
niloy opened this issue Sep 24, 2015 · 0 comments
Open

Get nested property from an Object #28

niloy opened this issue Sep 24, 2015 · 0 comments

Comments

@niloy
Copy link
Owner

niloy commented Sep 24, 2015

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"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant