Reputation: 382
I have javascript associative array following
var list = {};
list['a'] = 'one';
list['b'] = 'two';
list['c'] = 'two';
By jquery ajax, I want pass only values of list array in json format.
{"list":["one","two","two"]}
How can I do it?
Upvotes: 1
Views: 316
Reputation: 664297
There are no associative arrays in javascript, only objects whose properties have no order. That means if you wanted to build an array of them, you'd need to sort the properties first:
var list = {a:'one', b:'two', c:'two'};
var result = {list:[]},
keys = [];
for (var key in list)
keys.push(key);
keys.sort();
for (var i=0; i<keys.length; i++)
result.list[i] = list[keys[i]];
return JSON.stringify(result);
Or the same thing with some helper functions, which may not be supported natively by all browsers:
return {list: Object.keys(list).sort().map(function(key) { return list[key]; })};
Upvotes: 0
Reputation: 342635
var list = {};
list['a'] = 'one';
list['b'] = 'two';
list['c'] = 'two';
var newObj = {
"list": []
};
for (key in list) {
newObj.list.push(list[key]);
}
alert(JSON.stringify(newObj));
Upvotes: 0