gpt4 book ai didi

javascript - 通过 UID 定位对象的递归 JavaScript 函数

转载 作者:行者123 更新时间:2023-11-28 17:29:12 26 4
gpt4 key购买 nike

我在返回在此层次树中找到的元素时遇到问题。例如,如果我选择的项目是:

{
"UID": 49,
"GUID": "",
"LocationName": "Doctor Smith's Office",

"LocationType": {
"UID": 2,
"LocationTypeName": "Practice",
"Description": "other location"
}
}

我会将 UID 与下面的对象数组进行匹配。

{
UID: 2,
GUID: "",
LocationName: "USA",
ParentLocation: null,
subs: [{
UID: 42,
GUID: "",
LocationName: "New Jersey",
Description: "",
subs: [{
UID: 3,
GUID: "",
LocationName: "Essex County",
ParentLocation: null,
"subs":[
UID: 4,
LocationName: "Newark",
ParentLocation: 3,
"subs": [
{
"UID": 49,
"GUID": "",
"LocationName": "Doctor Smith's Office",

"LocationType": {
"UID": 2,
"LocationTypeName": "Practice",
"Description": "other location"
},
"subs": [
{
"HostID": 38,
"HostName": "Ocean Host",
}
]
}
]
]
}
]
}]
};

let foundItem = this.findInTreeView(this.treeviewData[0], node.selectedNode);

// find selected node in treeview nav
// param: data - the treeview dataset
// param: selected - the selected node to be searched for in param 'data'
findInTreeView(data: any, selected: any ) {
let found;
if (this.foundInTree(data, selected)) {
return data;
}
let elem;
let ary = data.subs;
for (var i=0; i < ary.length; i++) {
elem = ary[i];
if (this.foundInTree(elem, selected)) {
// *** PROBLEM: If func has return true, I want to return the 'elem' object.
return elem;
}
}
for (var i=0; i < ary.length; i++) {
elem = ary[i];
if (elem.subs !== undefined) {
// recurse subs array
let found = this.findInTreeView(elem, selected);
if (found) {
return elem;
}
}
}
//return elem;
}

foundInTree(treeItem, node) {
if (treeItem.UID === node.UID) {
return true;
}
else {
return false;
}
}

最佳答案

使用递归reduce函数会容易得多,如下所示:

const input={UID:2,GUID:"",LocationName:"USA",ParentLocation:null,subs:[{UID:42,GUID:"",LocationName:"New Jersey",Description:"",subs:[{UID:3,GUID:"",LocationName:"Essex County",ParentLocation:null,"subs":[{UID:4,LocationName:"Newark",ParentLocation:3,"subs":[{"UID":49,"GUID":"","LocationName":"Doctor Smith's Office","LocationType":{"UID":2,"LocationTypeName":"Practice","Description":"other location"},"subs":[{"HostID":38,"HostName":"Ocean Host",}]}]}]}]}]};

const findUIDObj = (uid, parent) => {
const { UID, subs } = parent;
if (UID === uid) {
const { subs, ...rest } = parent;
return rest;
}
if (subs) return subs.reduce((found, child) => found || findUIDObj(uid, child), null);
};
console.log(findUIDObj(49, input))

关于javascript - 通过 UID 定位对象的递归 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50846231/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com