如何在Javascript中将数组结果树从子父转换为父子

时间:2015-09-05 13:49:05

标签: javascript arrays

任何人都可以帮助我使用javascript函数来推翻这个后面的数组。这个结果是我从数据库得到的,打算用javascript做一些树。

[{
    SubCategoryId: 1,
    SubCategoryName: "SubCategoryName1",
    Category: {
        CategoryId: 11,
        CategoryName: "CategoryName1",
        MainCategory: {
            MainCategoryId: 111,
            MainCategoryName: "MainCategoryName1",
        }
    }
},{
    SubCategoryId: 2,
    SubCategoryName: "SubCategoryName2",
    Category: {
        CategoryId: 11,
        CategoryName: "CategoryName1",
        MainCategory: {
            MainCategoryId: 111,
            MainCategoryName: "MainCategoryName1",
        }
    }
},{
    SubCategoryId: 3,
    SubCategoryName: "SubCategoryName3",
    Category: {
        CategoryId: 22,
        CategoryName: "CategoryName2",
        MainCategory: {
            MainCategoryId: 111,
            MainCategoryName: "MainCategoryName1",
        }
    }
}]

我期待的结果是:

[{
    MainCategoryId: 111,
    MainCategoryName: "MainCategoryName1",
    Category: [{
        CategoryId: 11,
        CategoryName: "CategoryName1",
        SubCategory: [{
            SubCategoryId: 1,
            SubCategoryName: "SubCategoryName1",
        }, {
            SubCategoryId: 2,
            SubCategoryName: "SubCategoryName2",
        }]
    }, {
        CategoryId: 22,
        CategoryName: "CategoryName2",
        SubCategory: [{
            SubCategoryId: 3,
            SubCategoryName: "SubCategoryName3",
        }]
    }],
}]

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

function category (arr) {

    // Start with empty array
    ret = new Array();

    // Iterate arr
    for (var i = 0; i < arr.length; i++) {

        // Search MainCategory
        var match = false;
        var j = 0;
        for (j = 0; j < ret.length; j++) {
            if (ret[j].MainCategoryId == arr[i].Category.MainCategory.MainCategoryId) { match = true; break; }
        }

        // If not exist MainCategory
        if (!match) {
            ret.push({
                MainCategoryId: arr[i].Category.MainCategory.MainCategoryId,
                MainCategoryName: arr[i].Category.MainCategory.MainCategoryName,
                Category: []
            });
        }

        // Search Category
        match = false;
        var k = 0;
        for (k = 0; k < ret[j].Category.length; k++) {
            if (ret[j].Category[k].CategoryId == arr[i].Category.CategoryId) { match = true; break; }
        }

        // If not exist Category
        if (!match) {
            ret[j].Category.push({
                CategoryId: arr[i].Category.CategoryId,
                CategoryName: arr[i].Category.CategoryName,
                SubCategory: []
            });
        }

        // Insert Subcategory
        ret[j].Category[k].SubCategory.push({
            SubCategoryId: arr[i].SubCategoryId,
            SubCategoryName: arr[i].SubCategoryName
        });

    }

    // Return new array
    return ret;
}