9

(上下文)我从一堆元素中获取信息,这些元素收集到一个 JSON 对象中,然后传递到 MVC3 控制器,在那里它被反序列化为一个对象。

有“项目”和“项目设置”。目前,我在平面 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").each 函数下是添加设置的地方。我试过像'editedItems.settings.push..'这样的语法,但它返回一个语法错误。

任何帮助将不胜感激!

4

3 回答 3

14
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"
            }
        ]
    }
];
于 2012-05-07T15:49:26.183 回答
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)
于 2012-05-07T15:48:45.677 回答
1

您需要将平面数据数组 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);
    
}
于 2015-02-23T13:59:20.743 回答