How to convert json values ​​to comma separated string using javascript

I have a JSON string:

{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2} 

I want location_id as

3.2

+5
source share
8 answers

Plain:

 var data = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}] var result = data.map(function(val) { return val.location_id; }).join(','); console.log(result) 

I assume you need a string, so .join(',') if you want the array to just delete this part.

+13
source

You can add brackets to the string, JSON.parse string ( JSON.parse ) and the map ( Array#map ) property and the union ( Array#join ) result.

 var string = '{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}', array = JSON.parse('[' + string + ']'), result = array.map(function (a) { return a.location_id; }).join(); console.log(result); 
+2
source

 obj=[{"name":"Marine Lines","location_id":3}, {"name":"Ghatkopar","location_id":2}] var res = []; for (var x in obj) if (obj.hasOwnProperty(x)) res.push(obj[x].location_id); console.log(res.join(",")); 
+1
source

try it

  var obj = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}]; var output = obj.map( function(item){ return item.location_id; }); console.log( output.join(",") ) 
0
source

 var arr = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}]; var location_array = []; for( var i = 0; i < arr.length; i++ ) { location_array.push( arr[i].location_id ); }//for var location_string = location_array.join(","); console.log(location_string); 

Note. You may need to use JSON.parse () if arr initially in string format.

0
source

 var json = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}]; var locationIds = []; for(var object in json){ locationIds.push(json[object].location_id); } console.log(locationIds.join(",")); 
0
source

You can also look at .reduce and create a string manually

 var d = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}] var location_id_str = d.reduce(function(p, c) { return p ? p + ',' + c.location_id : c.location_id },''); console.log(location_id_str) 
0
source

You can use for..of

 var arr = [{ "name": "Marine Lines", "location_id": 3 }, { "name": "Ghatkopar", "location_id": 2 }]; var res = []; for ({location_id} of arr) {res.push(location_id)}; console.log(res); 
0
source

Source: https://habr.com/ru/post/1258192/


All Articles