2012-05-07 95 views
5

(上下文)我從一堆收集到JSON對象中的元素獲取信息,然後將其傳遞給一個MVC3控制器,並在該對象中進行反序列化。動態創建一個嵌套的JSON對象

有'項目'和'項目設置'。目前,我已將所有項目和項目設置都放在扁平的JSON對象中。理想情況下,我希望將項目設置嵌套在每個項目下。我的代碼目前看起來像這樣:

var editeditems=[]; 
... 

     $("#SaveChanges").click(function() { 

      //this works and retrieves all of the item IDs 
      $(".portlet").each(function() { 

       var itemname = $(this).data("itemname"); 
     editeditems.push(
         { 
          "itemname": itemname 
         }); 

    itemname = $(this).data("itemname"); 

     $(".settingInput").each(function() { 

      editeditems.push(
       { 
       "settingkey":$(this).attr("name"), 
       "settingvalue":$(this).attr("value") 
       }); 


       }); 


}); 

在$(「。settingInput」)下,每個函數都是添加設置的地方。我嘗試過像'editedItems.settings.push ..'這樣的語法,但它返回的語法錯誤。

任何幫助將不勝感激!

回答

12
var editeditems = []; 
... 

$('#SaveChanges').click(function() { 
    $('.portlet').each(function() { 
     var settings = []; 
     $('.settingInput').each(function() { 
      settings.push({ 
       settingkey: $(this).attr('name'), 
       settingvalue: $(this).attr('value') 
      }); 
     }); 

     editeditems.push({ 
      itemname: $(this).data('itemname'), 
      settings: settings 
     }); 
    }); 

    ... 
}); 

會產生輸出樣本:

var editeditems = 
[ 
    { 
     "itemname": "item1", 
     "settings": [ 
      { 
       "settingkey": "key1", 
       "settingvalue": "value1" 
      }, 
      { 
       "settingkey": "key2", 
       "settingvalue": "value2" 
      } 
     ] 
    }, 
    { 
     "itemname": "item2", 
     "settings": [ 
      { 
       "settingkey": "key1", 
       "settingvalue": "value3" 
      }, 
      { 
       "settingkey": "key2", 
       "settingvalue": "value4" 
      } 
     ] 
    } 
]; 
+0

這工作得很好!謝謝! – Scottingham

3
var ei = {'settings': [3]}; 
ei.settings.push(4); 
console.log(ei); 
// This will output an object with property settings and value an array with values (3 and 4) 
0

只要你需要創建平面數據數組JSON像

[{"itemname": "item1","settingkey": "key1","settingvalue": "value1"}, 
{"itemname": "item2","settingkey": "key2","settingvalue": "value2"},]; 

不僅僅是處理這樣

var keys = Object.keys(dataMap); 

var json = []; 
for (var key in keys) { 
     var innerJson = {}; 
     innerJson["name"] = keys[key]; 
     var innerMap = dataMap[keys[key]]; 

     if (innerMap instanceof Array) { 
      innerJson["size"] = innerMap[0]; 
     } else if (innerMap instanceof Object) { 

      var child = processHirarchiachalData(innerMap); 
      innerJson["children"] = child; 
     } 
     json.push(innerJson); 

}