我有以下对象的JSON列表,并且我能够找到所需的对象,并将其传递给调用方(给定id )。一切正常,我只是想知道是否有一种更好(更有效)的方法来返回节点。我愿意使用像lodash这样的第三方工具。
JSON有效载荷:
{
"_expanded": true,
"_canDrop": false,
"_id": "-1",
"_name": "root",
"_children": [
{
"_expanded": true,
"_canDrop": false,
"_id": "1",
"_name": "Child 1",
"_children": [
{
"_expanded": true,
"_canDrop": false,
"_id": "1-1",
"_name": "Child 1-1",
"_children": [
{
"_expanded": false,
"_canDrop": false,
"_id": "1-1-1",
"_name": "Child 1-1-1",
"_children": []
}
]
},
{
"_expanded": false,
"_canDrop": false,
"_id": "1-2",
"_name": "Child 1-2",
"_children": []
},
{
"_expanded": false,
"_canDrop": false,
"_id": "1-3",
"_name": "Child 1-3",
"_children": []
}
]
},
{
"_expanded": true,
"_canDrop": false,
"_id": "2",
"_name": "Child 2",
"_children": [
{
"_expanded": false,
"_canDrop": false,
"_id": "2-2",
"_name": "Child 2-2",
"_children": []
}
]
}
]
}查找方法:
public findNode = (id: any): TreeNode => {
let result = null;
if (this._id === id) {
result = this;
} else {
if (this._children.length > 0) {
for (let index = 0; index <= this._children.length - 1; index++) {
result = this._children[index].findNode(id);
if (result) {
break;
}
}
}
}
return result;
}发布于 2018-03-18 18:23:26
你的方法看起来已经不错了!我只会对逻辑作以下几个小小的改动:
if (this._children.length > 0)不是必需的,因为for循环将为您进行检查for..of循环。类型记录将转换这一点,因此它将在任何环境中工作。result变量存储在尽可能小的块中。有了这些变化:
public findNode = (id: any): TreeNode => {
if (this._id === id) {
return this;
}
for (const child of this._children) {
const result = child.findNode(id);
if (result) {
return result;
}
}
return null;
}另外,这里有几个打字本的特定注释:
any。当您使用any时,您正在告诉类型记录,以便有效地忽略代码中的任何错误。考虑到您的数据结构,看起来id应该是string类型。strictNullChecks。这将有助于防止一大类错误。public修饰符,因为它是多余的。但是,如果您与通常使用其他语言的开发人员一起工作,这并不适用,因为这可能会导致团队中的混乱。例如,在C#中,默认情况是所有方法都是private有了这些变化:
findNode = (id: string): TreeNode | null => {
if (this._id === id) {
return this;
}
for (const child of this._children) {
const result = child.findNode(id);
if (result) {
return result;
}
}
return null;
}https://codereview.stackexchange.com/questions/189874
复制相似问题