atredis
atredis

Reputation: 382

Associative array values to json

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

Answers (3)

Bergi
Bergi

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

karim79
karim79

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));​

Demo.

Upvotes: 0

VisioN
VisioN

Reputation: 145378

You may use $.map() to extract values:

$.ajax({
    data: {
        list: $.map(list, function(val) { return val; })
    },
    ...
});

Upvotes: 2

Related Questions