parse json nary tree to generate path of a key in javascript

To generate the path of a key in a JSON n-ary tree, we can use a recursive function. The function takes a tree node and a target key as its input. It checks if the current node has the target key. If it does, it returns the key path. If not, it recursively calls the function on each child of the current node.

Here's the code:

index.tsx
function generateKeyPath(node, targetKey, currentPath = []) {
  // get the keys of the current node
  const keys = Object.keys(node);

  // check if the target key is in the keys
  if (keys.includes(targetKey)) {
    return [...currentPath, targetKey];
  }

  // recursively call the function on each child of the current node
  for (const key of keys) {
    if (typeof node[key] === 'object' && node[key] !== null) {
      const path = generateKeyPath(node[key], targetKey, [...currentPath, key]);

      if (path) {
        return path;
      }
    }
  }

  // if the target key is not found in the tree, return null
  return null;
}
636 chars
24 lines

We can use this function to generate the path of a key in a JSON n-ary tree like this:

index.tsx
const tree = {
  name: 'root',
  children: [
    {
      name: 'child1',
      children: [
        { name: 'grandchild1' },
        { name: 'grandchild2' },
      ],
    },
    {
      name: 'child2',
      children: [
        { name: 'grandchild3' },
        { name: 'grandchild4' },
      ],
    },
  ],
};

const targetKey = 'grandchild3';
const keyPath = generateKeyPath(tree, targetKey);
console.log(keyPath); // output: ['children', 1, 'children', 0, 'name']
465 chars
24 lines

In this example, the target key is "grandchild3". The function returns the path to the key, which is ["children", 1, "children", 0, "name"]. This means that the key can be accessed in the tree like this: tree.children[1].children[0].name.

gistlibby LogSnag