Reputation: 11297
Hello I have a javascript question whereby I am getting a JSON result:
{"0":"San Diego acls","1":"San Diego pals","2":" San Diego CPR","3":" Temecula acls","4":" Temecula pals"}
which is stored in a variable called data.
I want to parse this data variable and make a list like:
San Diego acls, San Diego pals, San Diego CPR, Temecula acls, Temecula pals
Any elegant ways?
Thanks
Upvotes: 2
Views: 15455
Reputation: 44444
What you need is this:
var res = [];
for (var x in obj)
if (obj.hasOwnProperty(x))
res.push(obj[x]);
console.log(res.join(","));
And there's one more way of 'elegantly' doing it (taken from Alex's answer),
res = [];
Object.keys(obj).forEach(function(key) {
res.push(obj[key]);
});
console.log(res.join(","));
In case you need the result in that specific order, sorting the keys (that come from Object.keys(obj)
) before invoking forEach on the array will help. Something like this:
Object.keys(obj).sort().forEach(function(key) {
Upvotes: 5
Reputation: 1497
This one also works.
$(document).ready(function(){
var data = {"0":"San Diego acls","1":"San Diego pals","2":" San Diego CPR","3":" Temecula acls","4":" Temecula pals"};
var csv = $.map(data,function(data){ return data;});
alert(csv);
});
Upvotes: 0
Reputation:
This is very simple in Javascript. You can access the variable data
like this:
alert(data[0]);
which should alert "San Diego acls". Do the same for all of them using a loop. You can concatenate strings easily with the +
operator.
var result = "";
for (var dString in data) {
result += dString + ", ";
}
This will create a string called result
and add the elements of the strings in the array to it. It will also add ", " between each element as you described in the question.
Upvotes: 0