Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a nested JSON object dynamically

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

like image 964
Scottingham Avatar asked May 07 '12 15:05

Scottingham


2 Answers

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"
            }
        ]
    }
];
like image 188
Darin Dimitrov Avatar answered Nov 15 '22 04:11

Darin Dimitrov


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)
like image 3
Marian Zburlea Avatar answered Nov 15 '22 03:11

Marian Zburlea