首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从json中递归查找依赖项

从json中递归查找依赖项
EN

Stack Overflow用户
提问于 2020-02-06 21:56:19
回答 1查看 83关注 0票数 1
代码语言:javascript
复制
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":[]
    }
]
代码语言:javascript
复制
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"]);
            }
        }
    }
}

我试图从上面的数据中找到特定故事的相关故事,我使用上面的函数只获得一个级别的数据,但我希望像这样递归输出,

代码语言:javascript
复制
{
  "B-3": [
    {
      "B-4": [

      ],
      "B-5": [
        {
          "Number": "B-6",
        },
        {
          "Number": "B-7",
        }
      ]
    }
  ]
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-06 22:13:28

您可以将数据转换为哈希表,并通过使用递归获得依赖项。

它仍然是相当不清楚,你想用树叶做什么。

代码语言:javascript
复制
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);
代码语言:javascript
复制
.as-console-wrapper { max-height: 100% !important; top: 0; }

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60096619

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档