parse json nary tree by a given key in javascript

To parse a JSON n-ary tree by a given key in JavaScript, we can use a recursive tree traversal method. Here's an example implementation:

index.tsx
function parseJsonTreeByKey(tree, key) {
  let results = [];
  
  function traverse(node) {
    if (node[key]) {
      results.push(node[key]);
    }
    if (node.children) {
      for (let i = 0; i < node.children.length; i++) {
        traverse(node.children[i]);
      }
    }
  }

  traverse(tree);
  return results;
}

// Example usage
const jsonTree = {
  "id": 1,
  "name": "Root",
  "children": [
    {
      "id": 2,
      "name": "Child A",
      "value": "hello",
      "children": [
        {
          "id": 3,
          "name": "Grandchild 1",
          "value": "world"
        },
        {
          "id": 4,
          "name": "Grandchild 2"
        }
      ]
    },
    {
      "id": 5,
      "name": "Child B",
      "value": "foo",
      "children": [
        {
          "id": 6,
          "name": "Grandchild 3",
          "value": "bar"
        }
      ]
    }
  ]
};

console.log(parseJsonTreeByKey(jsonTree, 'value')); // Output: ["hello", "world", "foo", "bar"]
987 chars
56 lines

In this example, the parseJsonTreeByKey function takes two arguments: the JSON n-ary tree and the key to search by. It initializes an empty results array and defines a recursive traverse function.

The traverse function checks if the current node has a property matching the specified key. If it does, the value of that property is added to the results array. It then checks if the current node has children, and if it does, it recursively calls traverse on each child node.

Finally, the parseJsonTreeByKey function calls traverse on the root of the tree and returns the resulting array of values.

gistlibby LogSnag