how to convert json values in comma separated string using javascript

后端 未结 8 773
情话喂你
情话喂你 2021-01-18 06:29

I have following JSON string :

相关标签:
8条回答
  • 2021-01-18 07:04

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

    0 讨论(0)
  • 2021-01-18 07:14

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

    0 讨论(0)
  • 2021-01-18 07:16

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

    0 讨论(0)
  • 2021-01-18 07:16

    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 讨论(0)
  • 2021-01-18 07:19

    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.

    0 讨论(0)
  • 2021-01-18 07:22

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

    0 讨论(0)
提交回复
热议问题