I have an array of JSON in ajax response in javascript.
[{"id":1,"text":"apple"},{"id":2,"text":"mango"},{"id":3,"text":"banana"}]
I want to extract a comma separated list of ids like "1, 2, 3" from this JSON response. How can i do this?
I have an array of JSON in ajax response in javascript.
[{"id":1,"text":"apple"},{"id":2,"text":"mango"},{"id":3,"text":"banana"}]
I want to extract a comma separated list of ids like "1, 2, 3" from this JSON response. How can i do this?
First, you parse the JSON (if you didn't do that already):
var arr = JSON.parse('[{"id":1,"text":"apple"},{"id":2,"text":"mango"},{"id":3,"text":"banana"}]');
Then you loop the array to extract the id on each object. You can use the map method of arrays to loop and add the ids to a new array in one go:
var ids = arr.map(function(item) {
return item.id;
});
alert(ids.join(','));
Assuming your json is stored as a string jsonstr in your js code:
/*parse the JSON to a JS object*/
var data = JSON.parse(jsonstr);
var ids = [];
for(var i=0; i<data.length; i++){
//loop over the array and if the id is defined add it
if(typeof data[i].id !== "undefined"){
ids.push(data[i].id);
}
}
var a = [{
"id": 1,
"text": "apple"
}, {
"id": 2,
"text": "mango"
}, {
"id": 3,
"text": "banana"
}];
var ar = [];
for (var i = 0; i < a.length; i++) {
ar.push(a[i].id);
}
alert(ar.join(','))
About this:
x = [{"id":1,"text":"apple"},{"id":2,"text":"mango"},{"id":3,"text":"banana"}];
str = "";
for(i=0;i<x.length;i++)
{
str += x[i].id.toString() + ',';
}
str = str.substring(0, str.length - 1);
console.log(str);