Perform .join on value in array of objects

前端 未结 10 1499
囚心锁ツ
囚心锁ツ 2020-11-29 15:31

If I have an array of strings, I can use the .join() method to get a single string, with each element separated by commas, like so:

[\"Joe\", \"         


        
相关标签:
10条回答
  • 2020-11-29 16:01

    lets say the objects array is referenced by the variable users

    If ES6 can be used then the easiest solution will be:

    users.map(user => user.name).join(', ');
    

    If not, and lodash can be used so :

     _.map(users, function(user) {
         return user.name;
     }).join(', ');
    
    0 讨论(0)
  • 2020-11-29 16:02

    I don't know if there's an easier way to do it without using an external library, but I personally love underscore.js which has tons of utilities for dealing with arrays, collections etc.

    With underscore you could do this easily with one line of code:

    _.pluck(arr, 'name').join(', ')

    0 讨论(0)
  • 2020-11-29 16:05

    Well you can always override the toString method of your objects:

    var arr = [
        {name: "Joe", age: 22, toString: function(){return this.name;}},
        {name: "Kevin", age: 24, toString: function(){return this.name;}},
        {name: "Peter", age: 21, toString: function(){return this.name;}}
    ];
    
    var result = arr.join(", ");
    //result = "Joe, Kevin, Peter"
    
    0 讨论(0)
  • 2020-11-29 16:08

    try this

    var x= [
      {name: "Joe", age: 22},
      {name: "Kevin", age: 24},
      {name: "Peter", age: 21}
    ]
    
    function joinObj(a, attr) {
      var out = []; 
      for (var i=0; i<a.length; i++) {  
        out.push(a[i][attr]); 
      } 
     return out.join(", ");
    }
    
    var z = joinObj(x,'name');
    z > "Joe, Kevin, Peter"
    var y = joinObj(x,'age');
    y > "22, 24, 21"
    
    0 讨论(0)
提交回复
热议问题