JavaScript - converting object key value pairs to JSON -


i have javascript object 6 key value pairs:

my_type_1:"vegetable" my_type_2:"fruit" my_type_3:"dessert"  my_value_1: "carrot" my_value_2: "apple" my_value_3: "cake" 

i want construct json out of above object such generates following:

[{"vegetable":"carrot"},{"fruit":"apple"},{"dessert":"cake"}] 

edit:

for (j=0;j<3;j++) {     var tvarray = new array();     var stype = 'my_type_'+j+1;     var svalue = 'my_value_'+j+1;     tvarray['type']  = jsobject[stype];     tvarray['value'] = jsobject[svalue]; } 

the json.stringify doesn't produce desired output listed above.

how do this?

thanks

you need put parenthesis around j + 1. have gives 'my_type_01' , on.

var obj = {     my_type_1:"vegetable",     my_type_2:"fruit",     my_type_3:"dessert",      my_value_1: "carrot",     my_value_2: "apple",     my_value_3: "cake" };  var pairs = [], pair; for(var j = 0; j < 3; j++) {    pair = {};    pairs.push(pair);    pair[obj['my_type_' + (j+1)]] = obj['my_value_' + (j+1)]; }   console.log(json.stringify(pairs)); 

Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -