Json使用javascript使用层次结构树

时间:2017-09-14 10:57:12

标签: javascript json

我有一个JSON数组。我尝试转换嵌套的分层树。但它没有用。我需要使用这个JSON的分层树。

这是我的数据:

[{
    "_id" : "59b65ee33af7a11a3e3486c2",
    "C_TITLE" : "Sweet and Snacks",
    "C_PARENT" : "0",
    "C_ICON" : "",
    "C_IMAGE" : "59b65ee33af7a11a3e3486c2_sweets.jpg",
    "C_STATUS" : "Active"
}
{
    "_id" : "59b663d709da571dc3d79f49",
    "C_TITLE" : "Groceries",
    "C_PARENT" : "0",
    "C_ICON" : "",
    "C_IMAGE" : "59b663d709da571dc3d79f49_grocery.jpg",
    "C_STATUS" : "Active"
},
{
    "_id" : "59b6648209da571dc3d79f4a",
    "C_TITLE" : "Dals & Pulses",
    "C_PARENT" : "59b663d709da571dc3d79f49",
    "C_ICON" : "",
    "C_IMAGE" : "59b6648209da571dc3d79f4a_dals.jpg",
    "C_STATUS" : "Active"
},
{
    "_id" : "59b6657509da571dc3d79f4c",
    "C_TITLE" : "Rice & Rice products",
    "C_PARENT" : "59b663d709da571dc3d79f49",
    "C_ICON" : "",
    "C_IMAGE" : "59b6657509da571dc3d79f4c_rice.jpg",
    "C_STATUS" : "Active"
}]

我需要这样的输出

[
    {
        " _id" : "59b65ee33af7a11a3e3486c2",
        "C_TITLE" : "Sweet and Snacks",
        "C_PARENT" : "0",
        "C_ICON" : "",
        "C_IMAGE" : "59b65ee33af7a11a3e3486c2_sweets.jpg",
        "C_STATUS" : "Active",
        children:[]


    }
   ]

基于检查C_PARENT和_id。

1 个答案:

答案 0 :(得分:0)

基本上,您需要而不是

o[a.id]

o[a._id]

因为您的数据有_id作为密钥ID。

另一个问题是与root的严格比较,你需要一个字符串作为值'0',因为这是你拥有的值。



var data = [{ _id: "59b65ee33af7a11a3e3486c2", C_TITLE: "Sweet and Snacks", C_PARENT: "0", C_ICON: "", C_IMAGE: "59b65ee33af7a11a3e3486c2_sweets.jpg", C_STATUS: "Active" }, { _id: "59b663d709da571dc3d79f49", C_TITLE: "Groceries", C_PARENT: "0", C_ICON: "", C_IMAGE: "59b663d709da571dc3d79f49_grocery.jpg", C_STATUS: "Active" }, { _id: "59b6648209da571dc3d79f4a", C_TITLE: "Dals & Pulses", C_PARENT: "59b663d709da571dc3d79f49", C_ICON: "", C_IMAGE: "59b6648209da571dc3d79f4a_dals.jpg", C_STATUS: "Active" }, { _id: "59b6657509da571dc3d79f4c", C_TITLE: "Rice & Rice products", C_PARENT: "59b663d709da571dc3d79f49", C_ICON: "", C_IMAGE: "59b6657509da571dc3d79f4c_rice.jpg", C_STATUS: "Active" }],
    result = function (array, root) {
        var r = [], o = {};
        array.forEach(function (a) {
            a.children = o[a._id] && o[a._id].children; // change to a._id
            o[a._id] = a;                               // change to a._id
            if (a.C_PARENT === root) {                  // strict comparison!
                r.push(a);
                return;
            }
            o[a.C_PARENT] = o[a.C_PARENT] || {};
            o[a.C_PARENT].children = o[a.C_PARENT].children || [];
            o[a.C_PARENT].children.push(a);
        });
        return r;
    }(data, "0");                                       // "0" as root

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }