Home > Mobile >  How to search a tree that is object based?
How to search a tree that is object based?

Time:11-21

I have a tree, and I want find the correct node and insert data into the object.

const resultTree = {
  grand_parent: {
    parent: {
      child: {},
    },
    sibling: {
      cousin: {},
    },
  },
};

for example, insert grand_child into child.

so the result will look like this:

const resultTree = {
  grand_parent: {
    parent: {
      child: {
        grand_child: {}, // inserted grand_child here
      },
    },
    sibling: {
      cousin: {},
    },
  },
};

and I can insert more as needed, i.e. insert sibling into child

const resultTree = {
  grand_parent: {
    parent: {
      child: {
        grand_child: {}, 
        sibling: {} // inserted sibling here
      },
    },
    sibling: {
      cousin: {},
    },
  },
};

This is what I have now, but it's not working

const findAndInsert = (node: string, tree: Tree, parentNode: string) => {
  if (!!tree[parentNode]) {
    tree[parentNode][node] = {};
  } else {
    Object.keys(tree[parentNode]).forEach((n) => {
      findAndInsert(node, tree[n], parentNode);
    });
  }
};

CodePudding user response:

The main issue is Object.keys(tree[parentNode]), as you had just confirmed that parentNode key does not exist in tree. Instead you want to iterate the existing keys.

I would also suggest to stop looking further when you have made the insertion. You can achieve this by returning a boolean that indicates that insertion happened, and then use some instead of forEach. Also, you don't actually need the iteration over the keys, but the values, so use Object.values:

const findAndInsert = (node, tree, parentNode) => {
  if (!!tree[parentNode]) {
    tree[parentNode][node] = {};
    return true;
  }
  return Object.values(tree).some((n) =>
    findAndInsert(node, n, parentNode)
  );
};

const tree = {
  grand_parent: {
    parent: {
      child: {},
    },
    sibling: {
      cousin: {},
    },
  },
};

findAndInsert("grandchild", tree, "child");
findAndInsert("sibling", tree, "child");
console.log(tree);

CodePudding user response:

The idea is correct, it just seems like you have a typo, it's Object.keys(tree) instead of Object.keys(tree[parentNode]).

  • Related