简体   繁体   中英

how to convert json values in comma separated string using javascript

I have following JSON string :

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

I want location_id as

3,2

Simple:

 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 wanted a string, hence the .join(',') , if you want an array simply remove that part.

You could add brackets to the string, parse the string ( JSON.parse ) and map ( Array#map ) the property and the join ( Array#join ) the 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); 

 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(",")); 

try this

  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(",") ) 

 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 the arr is in string format initially.

 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(",")); 

You can also look into .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) 

You can use for..of loop

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM