Re-Structuring a JSON

后端 未结 2 884
鱼传尺愫
鱼传尺愫 2020-12-22 08:30

OK guys need some help out there. I\'m still learning Javascript and its interactions JSON. I have a a JSON like this

[{
  \"categories\":\"Food\",
  \"subca         


        
2条回答
  •  无人及你
    2020-12-22 09:13

    I workout a solution, but I'm not sure how it will handle big json data. Assume that the json var stores your data:

    categories = [];
    json.forEach(function(entry) {  
        var cindex = categories.map(function(category) { 
            return category.name; 
        }).indexOf(entry.categories);
    
        if (cindex < 0) {
            // Not found in categories array
            cindex = categories.push({
                name: entry.categories,
                subcategories: []
            }) - 1; // -1 to fix the index
        }
    
        // Lets search the subcategory
        var category = categories[cindex];
    
        var sindex = category.subcategories.map(
            function(subcategory) {
                return subcategory.name;
            }
        ).indexOf(entry.subcategories);
    
        if (sindex < 0) {
          // Not Found
            sindex = category.subcategories.push({
                name: entry.subcategories,
                items: []
            }) - 1; 
        } 
        // Subcategory exists. Just push
        category.subcategories[sindex].items.push({
            pid: entry.pid,        
            description: entry.description,
            title: entry.title
        });
    });
    
    var menu = {
        menu: {
            categories: categories
        }
    };
    

    Working Fiddle

提交回复
热议问题