JSFiddle - React, Tailwind, and code Playground

by sperske

JavaScript

class Child {
  constructor(node) {
    this.name = node.name
  }
}

class Parent extends Child {
  constructor(node) {
    super(node)
    this.children = []
    if (node.children) {
      for (const child of node.children) {
        this.children.push(child.children ? new Parent(child) : new Child(child))
      }
    }
  }
}

const data = {
  name: "Dineane",
  children: [{
    name: "Joey"
  }, {
    name: "Jason",
    children: [{
      name: "Piper"
    }, {
      name: "Q"
    }, {
      name: "Scout"
    }]
  }]
}

function* find(node, predciate) {
  if (predciate(node)) {
    yield node
  }
  if (node.children) {
    for (const child of node.children) {
      const result = find(child, predciate).next().value
      if (result) {
        yield child
      }
    }
  }
}

const jason = find(data, (node) => node.name === 'Zach').next().value
if(jason) {
console.log(new Parent(jason))
}