bksoni
bksoni

Reputation: 363

Create nested json object using jquery

Using json object not from array.

$(document).ready(function () { 
    var editeditems = {}; 
    var address = {};
    var firstName;
    var lasteName; 
    $('#btnJson').click(function () { 
        for (var i = 0; i < 3; i++) { 
            address["street"] = i; 
            address["city"] = i; 
        } 
        editeditems["FirstName"] = "mehul"; 
        editeditems["LastName"] = "gohel"; 
        editeditems["Address"] = address; 
        $('#txtVal').text(JSON.stringify(editeditems)); 
    }); 
});

I am using this code and get output of:

{
   "firstName": "Mehul",
   "lasteName": "Gohel",
   "address": [
      {
         "Street": 0,
         "City": 0
      },
      {
         "Street": 1,
         "City": 1
      }
   ]
}

Upvotes: 3

Views: 13826

Answers (1)

Wangot
Wangot

Reputation: 91

Here is one way:

$(document).ready(function () { 
  $('#btnJson').click(function () { 
    var jsonObj = {}; 
    var addressArray = [];

    for (var i = 0; i < 3; i++) { 
        var address = {}
        address.street = i; 
        address.city = i; 
        addressArray.push(address);
    } 

    jsonObj.FirstName = "mehul"; 
    jsonObj.LastName = "gohel"; 
    jsonObj.Address = addressArray;  

    $('#txtVal').text(JSON.stringify(jsonObj)); 
  });
});

Another one:

$(document).ready(function () { 
  $('#btnJson').click(function () { 
    var jsonObj = {
      "FirstName":"mehul",
      "LastName":"gohel",
      "Address":[]
    }; 

    for (var i = 0; i < 3; i++) { 
        var address = {}
        address.street = i; 
        address.city = i; 
        jsonObj.Address.push(address);
    } 

    $('#txtVal').text(JSON.stringify(jsonObj)); 
  });
}); 

And you will get this result:

{
  "FirstName":"mehul",
  "LastName":"gohel",
  "Address":[
    {"street":0,"city":0},
    {"street":1,"city":1},
    {"street":2,"city":2}
  ]
}

Upvotes: 2

Related Questions