0

I am trying to Search in a tree, but my results are not as expected. Can any body please help?

function treeSearch(searchedValue,ExceptionTree:){
    let result = {};
    var childrenKeys = Object.keys(ExceptionTree);
    for(let i = 0; i< childrenKeys.length;i++){
        if(childrenKeys[i].toLowerCase().indexOf(searchedValue) >=0 ||  Object.keys( treeSearch( ExceptionTree[childrenKeys[i]] , searchedValue  ) ).length >=0 )
          result[childrenKeys[i]] = ExceptionTree[childrenKeys[i]];
    }
    return result;
}

Below is the sample Input:

var myTree= {
  "North America": {
    "Canada": {
      "VanCouver": 1,
      "Ottawa": 2
    },
    "US": {
      "Florida": 3,
      "Texas": 4
    }
  },
  "Asia": {
    "India": {
      "Mumbai": 5,
      "Delhi": 6
    },
    "China": {
      "Shanghai": 9,
      "Beijing": 10
    }
  }
}   

If I call

treeSearch("Texas",myTree)

the result should be

{
      "North America": {
        "USA": {
          "Texas":4
      }
    }
}

I am either getting the entire tree returned or an empty tree. Any suggestions?

Murtuza Husain
  • 178
  • 2
  • 14

2 Answers2

1

Try this (details in comments):

// Insert your tree and text to find
function treeSearch(tree, text) {
    let result = null;

    // Loop input tree
    for (const [key, value] of Object.entries(tree)) {
        if (typeof(value) === "object") {
            // Recursive call on an sub-objects
            const found = treeSearch(value, text);
            if (found) {
                result = { [key]: found };
            }
        } else if (key === text) {
            // Result found
            result = { [key]: value };
        }
    }

    return result;
}

const result = treeSearch(myTree, "Texas");

Result is an object below or null if text wasn't found

{
    North America: {
        US: {
            Texas: 4
        }
    }
}
jrck
  • 119
  • 1
  • 2
  • 6
0

Here is an iterative solution using object-scan

// const objectScan = require('object-scan');

const myTree = { 'North America': { Canada: { VanCouver: 1, Ottawa: 2 }, US: { Florida: 3, Texas: 4 } }, Asia: { India: { Mumbai: 5, Delhi: 6 }, China: { Shanghai: 9, Beijing: 10 } } };

const treeSearch = (name, tree) => objectScan(['*.*.*'], {
  abort: true,
  filterFn: ({ property, key, value, context }) => {
    if (property !== name) {
      return false;
    }
    key.reduce((p, c, idx) => {
      p[c] = idx === key.length - 1 ? value : {};
      return p[c];
    }, context);
    return true;
  }
})(tree, {});

console.log(treeSearch('Texas', myTree));
// => { 'North America': { US: { Texas: 4 } } }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.8.0"></script>

Disclaimer: I'm the author of object-scan

vincent
  • 1,953
  • 3
  • 18
  • 24