data = [
{
"StoryID":"B-1",
"Dependencies":[{"StoryID":"B-2",},{"StoryID":"B-3",}]
},
{
"StoryID":"B-2",
"Dependencies":[]
},
{
"StoryID":"B-3",
"Dependencies":[{"StoryID":"B-4",},{"StoryID":"B-5",}]
},
{
"StoryID":"B-4",
"Dependencies":[]
},
{
"StoryID":"B-5",
"Dependencies":[{"StoryID":"B-6"}]
},
{
"StoryID":"B-6",
"Dependencies":[]
}
]var storyID = "B-3";
get_d(data,storyID ,Dependencies = []);
function get_d(data,storyID ,Dependencies = []){
temp = []
for(i in data){
if(storyID == data[i]['StoryID']){
depend = data[i]['Dependencies'];
for(j in depend){
Dependencies.push(depend[j]["StoryID"]);
}
}
}
}我试图从上面的数据中找到特定故事的相关故事,我使用上面的函数只获得一个级别的数据,但我希望像这样递归输出,
{
"B-3": [
{
"B-4": [
],
"B-5": [
{
"Number": "B-6",
},
{
"Number": "B-7",
}
]
}
]
}发布于 2020-02-06 22:13:28
您可以将数据转换为哈希表,并通过使用递归获得依赖项。
它仍然是相当不清楚,你想用树叶做什么。
function getDependencies(data, StoryID) {
function getProperty(k) {
return function (o) { return o[k]; };
}
function getD(r, StoryID) {
r[StoryID] = object[StoryID].reduce(getD, {});
return r;
}
var object = data.reduce(function (r, o) {
r[o.StoryID] = (o.Dependencies || []).map(getProperty('StoryID'));
return r;
}, {});
return [StoryID].reduce(getD, {});
}
var data = [{ StoryID: "B-1", Dependencies: [{ StoryID: "B-2" }, { StoryID: "B-3" }] }, { StoryID: "B-2", Dependencies: [] }, { StoryID: "B-3", Dependencies: [{ StoryID: "B-4" }, { StoryID: "B-5" }] }, { StoryID: "B-4", Dependencies: [] }, { StoryID: "B-5", Dependencies: [{ StoryID: "B-6" }] }, { StoryID: "B-6", Dependencies: [] }],
result = getDependencies(data, 'B-3')
console.log(result);.as-console-wrapper { max-height: 100% !important; top: 0; }
https://stackoverflow.com/questions/60096619
复制相似问题