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

Answers:

Answer

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.

Answer

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

Answer

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

Answer

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

Answer

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.

Answer

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

Answer

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)

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.