Perform .join on value in array of objects

前端 未结 10 1510
囚心锁ツ
囚心锁ツ 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:00

    If you want to map objects to something (in this case a property). I think Array.prototype.map is what you're looking for if you want to code functionally.

    [
      {name: "Joe", age: 22},
      {name: "Kevin", age: 24},
      {name: "Peter", age: 21}
    ].map(function(elem){
        return elem.name;
    }).join(",");
    

    In modern JavaScript:

    [
      {name: "Joe", age: 22},
      {name: "Kevin", age: 24},
      {name: "Peter", age: 21}
    ].map(e => e.name).join(",");
    

    (fiddle)

    If you want to support older browsers, that are not ES5 compliant you can shim it (there is a polyfill on the MDN page above). Another alternative would be to use underscorejs's pluck method:

    var users = [
          {name: "Joe", age: 22},
          {name: "Kevin", age: 24},
          {name: "Peter", age: 21}
        ];
    var result = _.pluck(users,'name').join(",")
    

提交回复
热议问题