Create a nested JSON object dynamically

2019-04-08 06:55发布

问题:

(context)I have information from a bunch of elements that I'm collecting into a JSON object that then gets passed down to an MVC3 controller where it gets deserialized into an object.

There are 'items' and 'item settings'. Currently, I have have both items and item settings all in flat JSON object. Ideally I would like to have the item settings nested under each item. My code currently looks like this:

 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")
              });


                });


 });

Under the $(".settingInput").each function is where the settings get added. I've tried syntax like 'editedItems.settings.push..' but it returns with a syntax error.

Any help would greatly be appreciated!

回答1:

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
        });
    });

    ...
});

will generate sample output:

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


回答2:

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)


回答3:

Just you need to create flat data array json like

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

Than just process like this

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);

}