tim@kolberger.eu
Photo by Bruno Nascimento on Unsplash

How to traverse an object

⚠️ This page is under construction

const obj = {
  this: {
    is: {
      a: {
        long: {
          path: ['I am in an Array at Postion 0'],
        },
      },
    },
  },
};
const DELIMITER = ';';
const pathString = 'this;is;a;long;path;0';
const nonExistingPathString = 'this;is;wrong';
function traverse(obj: any, path: string | string[], delimiter: string = '.') {
  function innerTraverse(
    obj: any,
    path: string | string[],
    delimiter: string,
    alreadyTraversed = []
  ) {
    // split string to an array
    if (typeof path === 'string') {
      path = path.split(delimiter);
    }

    // error handling
    if (obj === undefined) {
      throw Error('No object found at ' + alreadyTraversed.join(delimiter));
    }

    // abort criterion
    if (!path.length) {
      return obj;
    }

    // remove traversed key
    const key = path.shift();

    // keep track of already traversed keys for better error message
    alreadyTraversed.push(key);

    // do it again
    return innerTraverse(obj[key], path, delimiter, alreadyTraversed);
  }

  return innerTraverse(obj, path, delimiter);
}

Try it on CodeSandbox

CodeSandBox | Traverse an object
© 2021 Tim KolbergerDatenschutzerklärung