重构JSON

时间:2014-01-10 00:34:56

标签: javascript json

好的家伙需要一些帮助。我还在学习Javascript及其交互JSON。我有一个像这样的JSON

[{
  "categories":"Food",
  "subcategories":"Shares",
  "pid":"111",
  "title":"Smoked Salmon Dip",
  "description":"Rich and savory salmon dip, whipped with fresh dill accompanied with     croustades"
   },
   {
  "categories":"Food",
  "subcategories":"Shares",
  "pid":"112",
  "title":"Sweet Goat Cheese Flatbread",
  "description":"Delicate grilled Naan flatbread coated with delish tomato jam and topped with melted goat cheese, roasted garlic, fennel, onion, pear, shiitake mushroom and arugula."
 },
 {
  "categories":"Food",
  "subcategories":"Snacks",
  "pid":"100",
  "title":"Beer Chili",
  "description":"Hot & satisfying short rib chili with black beans, smoked jalapenos, and fresh corn. Topped with aged cheddar cheese and sour cream."
 }];

但我需要的是一个看起来像这样的JSON

{
 "menu":{
  "categories":[
     {
                "name":"Food",
                "subcategories":[
                    {
                    "name":"Shares",
                    "items":[
                        {
                        "pid":"111",
                        "title":"Smoked Salmon Dip",
                        "description":"Rich and savory salmon dip, whipped with fresh dill accompanied with croustades"
                        },
                        {
                        "pid":"112",
                        "title":"Sweet Goat Cheese Flatbread",
                        "description":"Delicate grilled Naan flatbread coated with delish tomato jam and topped with melted goat cheese, roasted garlic, fennel, onion, pear, shiitake mushroom and arugula."
                        }
                        ]
                    },
                    {
                    "name":"Snacks",
                    "items":[
                        {                       
                        "pid":"100",
                        "title":"Beer Chili",
                        "description":"Hot & satisfying short rib chili with black beans, smoked jalapenos, and fresh corn. Topped with aged cheddar cheese and sour cream."
                        }
                        ]
                    }
                    ]
        }]
        }
     }

我知道它有点难看但我在查找如何构建新JSON时遇到了麻烦,因为我遍历了当前的JSON。

让我前进的任何帮助都很棒

2 个答案:

答案 0 :(得分:0)

我锻炼了一个解决方案,但我不确定它将如何处理大型json数据。假设json var存储您的数据:

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

答案 1 :(得分:0)

我给了他一个镜头,也可以发布我的结果。数据与您的数据并不完美排列。它不需要jQuery,它可以用于多次排序数据。

Object.prototype.groupBy = function(itemName, preGrouped)
{
    if(preGrouped)
    {
        for(prop in this)
        {
            if(typeof(this[prop]) === 'object' && this[prop].groupBy !== undefined)
            {
                var reGroup = this[prop].groupBy(itemName);  
                this[prop] = reGroup;
            }
        }
        return this;
    }
    else
    {
        var uniqueItems = {};
        var uniqueItemLength = 0;
        for(var i=0, length=this.length; i < length; i++)
        {
           var item = this[i]; 
           var z =0;
           var found = false;
           while(z < uniqueItemLength)
           {     
               if(item[itemName] in uniqueItems)
               {
                   uniqueItems[item[itemName]].push(item);
                   found = true;
                   break;
               }
               z++;
           }
            if(!found)
            {
                uniqueItems[item[itemName]] = [];
                uniqueItems[item[itemName]].push(item); 
                uniqueItemLength++;
            }      
        }
        return uniqueItems;
    } 
}

它被调用:

var convertedData = oldJSON.groupBy('categories').groupBy('subcategories', true)

Beterraba的回答是正确的。我花了一些时间在这一个,并认为我至少发布。也许它会帮助别人。

http://jsfiddle.net/8VRuy/