Create a JSON tree in Node.Js from MongoDB

后端 未结 1 1462
离开以前
离开以前 2021-02-04 22:14

I am trying for a couple of days to create a JSON tree from my MongoDB. I use the child reference model structure, where \"Books\" is the root node.
I am trying to achieve a

1条回答
  •  我在风中等你
    2021-02-04 22:37

    Lets say that you have to following data (already loaded from db):

    var data = [
      { _id: "MongoDB", children: [] },
      { _id: "Postgres", children: [] },
      { _id: "Databases", children: [ "MongoDB", "Postgres" ] },
      { _id: "Languages", children: [] },
      { _id: "Programming", children: [ "Databases", "Languages" ] },
      { _id: "Books", children: [ "Programming" ] }
    ];
    

    Since _id is unique, then in first step you convert it to dictionary, where keys are ids:

    var dct = {};
    for (var i = 0; i < data.length; i++) {
        var doc = data[i];
        dct[doc._id] = doc;
    }
    

    Now you loop through data array one more time and set children:

    for (var i = 0; i < data.length; i++) {
        var doc = data[i];
        var children = doc.children;
        var ref_children = [];
        for (var j = 0; j < children.length; j++) {
            var child = dct[children[j]]; // <-- here's where you need the dictionary
            ref_children.push(child);
        }
        doc.children = ref_children;
    }
    

    And voila, you're done:

    JSON.stringify(data);
    

    EDIT

    If you want only roots (nodes which are not children of any other node), then first you have to find them:

    var get_parent = function(node, docs) {
        for (var i = 0; i < docs.length; i++) {
            var doc = docs[i];
            if (doc.children.indexOf(node) != -1) {
                return doc;
            }
        }
        return null;
    };
    
    var roots = [];
    for (var i = 0; i < docs.length; i++) {
        var doc = data[i];
        if (get_parent(doc, docs) === null) {
            roots.push(doc);
        }
    }
    JSON.stringify(roots);
    

    More efficient way would be to store parents when dereferencing children (compare with the code above EDIT):

    for (var i = 0; i < data.length; i++) {
        var doc = data[i];
        var children = doc.children;
        var ref_children = [];
        for (var j = 0; j < children.length; j++) {
            var child = dct[children[j]]; // <-- here's where you need the dictionary
            child.has_parent = true; // <-- has a parent
            ref_children.push(child);
        }
        doc.children = ref_children;
    }
    
    var roots = [];
    for (var i = 0; i < data.length; i++) {
        var doc = data[i];
        if (!doc.has_parent) {
            roots.push(doc);
        }
    }
    JSON.stringify(roots);
    

    0 讨论(0)
提交回复
热议问题