我有以下JSON字符串:
{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}

我希望location_id为
3,2
答案 0 :(得分:13)
简单:
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(',')
,如果您想要一个数组,只需删除该部分。
答案 1 :(得分:2)
您可以在字符串中添加括号,解析字符串(JSON.parse
)并映射(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);

答案 2 :(得分:1)
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(","));

答案 3 :(得分:0)
试试这个
{{1}}
答案 4 :(得分:0)
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()。
答案 5 :(得分:0)
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(","));
答案 6 :(得分:0)
您还可以查看.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)
答案 7 :(得分:0)
您可以使用foooof
循环
for..of
&#13;