Create a nested JSON object dynamically

asp.net-mvc-3, javascript, jquery

Solution

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

Problem

(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!

Original source