繁体   English   中英

如何使用javascript在逗号分隔的字符串中转换json值

[英]how to convert json values in comma separated string using javascript

我有以下JSON字符串:

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

我想把location_id作为

3,2

简单:

 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) 

我假设您想要一个字符串,因此.join(',') ,如果您想要一个数组只是删除该部分。

您可以在字符串中添加括号,解析字符串( JSON.parse )和map( Array#map )属性以及连接( Array#join )结果。

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

试试这个

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

注意:如果arr最初是字符串格式,则可能需要使用JSON.parse()。

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

您还可以查看.reduce并手动创建字符串

 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) 

你可以使用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); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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