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
}
]
}
Theodore K.
5,2064 gold badges32 silver badges47 bronze badges
asked Nov 23, 2016 at 11:04
bksoni
3731 gold badge4 silver badges11 bronze badges
-
What is your question?B001ᛦ– B001ᛦ2016年11月23日 11:05:44 +00:00Commented Nov 23, 2016 at 11:05
-
Please explain your question, and also include the codes you have tried so far. That will help people to understand your question. ThanksSibeesh Venu– Sibeesh Venu2016年11月23日 11:14:24 +00:00Commented Nov 23, 2016 at 11:14
-
$(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","LastName":"gohel","Address":{"street":2,"city":2}}bksoni– bksoni2016年11月23日 11:29:50 +00:00Commented Nov 23, 2016 at 11:29
1 Answer 1
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}
]
}
Sign up to request clarification or add additional context in comments.
1 Comment
Wangot
The second solution is just the same with different approach.
Explore related questions
See similar questions with these tags.
lang-js