Simple method to return comma-separated values of object array

后端 未结 2 1745
独厮守ぢ
独厮守ぢ 2020-12-21 02:56

I have an object that looks like this:

{
  \"id\": \"123\",
   \"members\": [
     { \"id\": 1, \"name\": \"Andrew\" },
     { \"id\": 2, \"name\": \"Jim\" }         


        
相关标签:
2条回答
  • 2020-12-21 03:13

    something like

    var arr = {
      "id": "123",
       "members": [
         { "id": 1, "name": "Andrew" },
         { "id": 2, "name": "Jim" }
       ]
    };
     console.log( arr.members.reduce( function(x,y){ return "\"" + x.name + "\", \"" + y.name + "\"" } ) );
    
    0 讨论(0)
  • 2020-12-21 03:32

    members is Array of Objects, first you need to create Array with names - for this case you can use .map and then convert this Array to String - to do that you can use .join

    var data = {
      "id": "123",
       "members": [
         { "id": 1, "name": "Andrew" },
         { "id": 2, "name": "Jim" }
       ]
    };
    
    var result = data.members.map(function (e) {
      return e.name;
    }).join(', ');
    
    console.log(result);

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