Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
138
rated 0 times [  144] [ 6]  / answers: 1 / hits: 20712  / 13 Years ago, wed, february 29, 2012, 12:00:00

I use datatables.net jQuery plugin to work with ajax tables. I want to send a POST request with JSON data in it. I use JSON.stringify to turn my data into JSON. It produces the result like this:



[
{name:sEcho,value:1},
{name:iColumns,value:9},
{name:sColumns,value:},
{name:iDisplayStart,value:0}
...]


Though I want it to be like this:



{sEcho:1, iColumns:9, sColumns:, iDisplayStart:0} ...


How can I do it?


More From » html

 Answers
163

You may iterate over your data and build the desired structure before JSON.stringify-ing it:



var data = [{name:sEcho,value:1},{name:iColumns,value:9},{name:sColumns,value:},{name:iDisplayStart,value:0}];

var options = {};
for (var i=0; i < data.length; i++){
var key = data[i].name;
var val = data[i].value;
options[key] = val;
}

var jsonString = JSON.stringify(options);


You may also save a couple of lines and make it looks a bit nicer using jQuery each method:



var options = {};
$.each(data, function(){
options[this.name] = this.value;
});

[#87134] Tuesday, February 28, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaia

Total Points: 574
Total Questions: 109
Total Answers: 110

Location: Malaysia
Member since Wed, May 11, 2022
2 Years ago
;