Suphakrit Phantharat Suphakrit Phantharat - 4 months ago 20
JSON Question

javascript arrays and JSON

I'm working on Bootstrap calendar and I've tried to make my array looks like this:

{
"success": 1,
"result": [
{
"id": "293",
"title": "This is warning class event with very long title to check how it fits to evet in day view",
"url": "http://www.example.com/",
"class": "event-warning",
"start": "1362938400000",
"end": "1363197686300"
},
{
"id": "256",
"title": "Event that ends on timeline",
"url": "http://www.example.com/",
"class": "event-warning",
"start": "1363155300000",
"end": "1363227600000"
},
{
"id": "276",
"title": "Short day event",
"url": "http://www.example.com/",
"class": "event-success",
"start": "1363245600000",
"end": "1363252200000"
},
{
"id": "294",
"title": "This is information class ",
"url": "http://www.example.com/",
"class": "event-info",
"start": "1363111200000",
"end": "1363284086400"
}
] }


But I've tried and got something like this:

[
{
"success":1
},
{
"result":[
{
"id":"1",
"title":"dev",
"url":"www.example.com",
"class":"event-success",
"start":"0",
"end":"0"
},
{
"id":"2",
"title":"Holiday",
"url":"www.example.com",
"class":"event-success",
"start":"0",
"end":"0"
},
{
"id":"3",
"title":"Coding...",
"url":"www.example.com",
"class":"event-success",
"start":"0",
"end":"0"
},
{
"id":"4",
"title":"data",
"url":"www.example.com",
"class":"event-success",
"start":"0",
"end":"0"
}
]
}
]


and my code to create those mess are

var result = [];
for(i=0; i<rows.length; i++) {
var result_single = {id:rows[i].uid, title:rows[i].name, url:"www.example.com", class:"event-success", start:rows[i].startdate, end:rows[i].enddate};
result.push(result_single);
}
var output = new Array();
output.push(data);
result = {result:result};
output.push(result);
console.log(JSON.stringify(output));


To be honest, I don't quite understand how array in js works. can somebody point out how did i go wrong?

Answer

Your expected result is an object which contains 2 properties, but you get an array which contains two objects. I think you want the first result which is object with two properties.

var result = [];
var rows = [1,2,3,4,5];

for(i=0; i<rows.length; i++) {
    var result_single = {id:rows[i], title:rows[i], url:"www.example.com", class:"event-success",                                 start:rows[i].startdate, end:rows[i].enddate};
    result.push(result_single);
}
    
var output = {
   success: 1,
   result: result
}
      
console.log(JSON.stringify(output));

Comments