基于各个级别的键搜索整个JSON树



我正在尝试在树中搜索,但结果并不像预期的那样。有人能帮忙吗?

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;
}

以下是示例输入:

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
}
}
}   

如果我打电话给

treeSearch("Texas",myTree)

结果应该是

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

我要么把整棵树还回来,要么把一棵空树还给我。有什么建议吗?

试试这个(细节在评论中(:

// 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");

结果是下方的对象,或者如果未找到文本则为空

{
North America: {
US: {
Texas: 4
}
}
}

以下是使用对象扫描的迭代解决方案

// 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>

免责声明:我是物体扫描的作者

最新更新