如何在打字稿中的树内找到树

时间:2018-11-06 16:24:57

标签: javascript arrays typescript recursion ecmascript-6

假设我在javascript中有一棵树

a1 
--b
----c1
a2
--b2
--b3
----c2

如果我想找到c2,它应该返回a2-> b3-> c2

可以说我的json看起来像这样吗?

treeFamily = {
            name : "Parent",
            children: [{
                name : "Child1",
                children: [{
                    name : "Grandchild1",
                    children: []
                },{
                    name : "Grandchild2",
                    children: []
                },{
                    name : "Grandchild3",
                    children: []
                }]
            }, {
                name: "Child2",
                children: []
            }]
        };

2 个答案:

答案 0 :(得分:1)

您可以检查嵌套的子代是否具有所需的键/值。然后使用function findPath(array, target) { var path; array.some(({ name, children }) => { var temp; if (name === target) { path = [name]; return true; } if (temp = findPath(children, target)) { path = [name, ...temp]; return true; } }); return path; } var treeFamily = { name: "Parent", children: [{ name: "Child1", children: [{ name: "Grandchild1", children: [] }, { name: "Grandchild2", children: [] }, { name: "Grandchild3", children: [] }] }, { name: "Child2", children: [] }] }; console.log(findPath([treeFamily], 'Grandchild2')); console.log(findPath([treeFamily], 'foo'));并将结果移交给外部调用。

var AWS = require('aws-sdk');
var dynamoClient = new AWS.DynamoDB.DocumentClient();    
var params = {
    "RequestItems": {
        "table_01": {
            "Keys": [{
                "std_id": "A_H_61_15"
            }, {
                "std_id": "A_H_61_23"
            }, ...]
        }
    }
}

var dynamoBatchGetPromise = dynamoClient.batchGet(params).promise();
dynamoBatchGetPromise.then(function (data) {
   console.log("data resp: " + JSON.stringify(data));
});

答案 1 :(得分:1)

您可以使用for...of通过递归调用函数来搜索子项。如果找到目标,则返回名称,并与先前的名称组合。否则,该函数将返回undefined。或者,您可以返回一个空数组。

const findPath = (targetName, { name, children }) => {
  if(name === targetName) return [name];
  
  for(const child of children) {
    const result = findPath(targetName, child);
    if(result) return [name, ...result];
  }
  
  // if child not found implicitly return undefined or return [] to get an empty array
};

const treeFamily = { name: "Parent", children: [{ name: "Child1", children: [{ name: "Grandchild1", children: [] }, { name: "Grandchild2", children: [] }, { name: "Grandchild3", children: [] }] }, { name: "Child2", children: [] }] };

console.log(findPath('Child2', treeFamily));
console.log(findPath('Grandchild3', treeFamily));
console.log(findPath('Grandchild400', treeFamily));