-2

Let's say there is a function:

/*

  • Write method findPath

  • Should take two params:

    • object

    • keys separated by dots as string

  • Return value if it exists at that path inside the object, else return undefined

*/

var obj = {
  a: {
    b: {
      c: 12,
      j: false,
    },
    k: null,
  },
};



console.log(findPath(obj, "a.b.c")); // 12
console.log(findPath(obj, "a.e.f.b.c"));

console.log(findPath(obj, "a.b")); // {c: 12, j: false}

console.log(findPath(obj, "a.b.d")); // undefined

console.log(findPath(obj, "a.c")); // undefined

console.log(findPath(obj, "a.b.c.d")); // undefined

console.log(findPath(obj, "a.b.c.d.e")); // undefined

console.log(findPath(obj, "a.b.j")); //false

console.log(findPath(obj, "a.b.j.k")); //undefined

console.log(findPath(obj, "a.k")); //null
  • SO is not a coding service, please make an attempt first – depperm Dec 15 '22 at 13:53
  • @depperm I have already solved the question but feels like not a good solution or not an efficient approach. And unable to proceed with any other way, hence posted here. – Mohit Pandey Dec 15 '22 at 13:55
  • see also https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-and-arrays-by-string-path – depperm Dec 15 '22 at 13:56
  • 1
    if you have a solution, try code review SE. If there is a bug, post [mcve] – depperm Dec 15 '22 at 13:56
  • 1
    Before you post at [codereview.se], make sure to read [A guide to Code Review for Stack Overflow users](//codereview.meta.stackexchange.com/a/5778), as some things are done differently over there - e.g. question titles should simply say what the code *does*, as the question is always, "How can I improve this?". Be sure that the code works correctly; include your unit tests if possible. You'll likely get some suggestions on making it more efficient, easier to read, and better tested. – Toby Speight Dec 15 '22 at 14:02

1 Answers1

1

universal but redundant if path is deep and doesn't exist

const findValue = (object, pathString) => {
    const path = pathString.split('.');
    let i = 0;
    const loop = (obj) => {
        const value = obj?.[path[i]];
        i++;
        if (i < path.length) {
            return loop(value);
        } else {
            return value;
        }
    }
    return loop(object)
}

same but breaks at not existing path

const findValue2 = (object, pathString) => {
    const path = pathString.split('.');
    let i = 0;
    const loop = (obj) => {
        const value = obj[path[i]];
        i++;
        if (i < path.length) {
            return loop(value);
        } else {
            return value;
        }
    }
    try {
        return loop(object);
    } catch(e) {
        return undefined;
    }
}
kosiakMD
  • 923
  • 7
  • 22