Perform .join on value in array of objects

前端 未结 10 1525
囚心锁ツ
囚心锁ツ 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 15:54

    I've also come across using the reduce method, this is what it looks like:

    [
      {name: "Joe", age: 22},
      {name: "Kevin", age: 24},
      {name: "Peter", age: 21}
    ].reduce(function (a, b) {return (a.name || a) + ", " + b.name})
    

    The (a.name || a) is so the first element is treated correctly, but the rest (where a is a string, and so a.name is undefined) isn't treated as an object.

    Edit: I've now refactored it further to this:

    x.reduce(function(a, b) {return a + ["", ", "][+!!a.length] + b.name;}, "");
    

    which I believe is cleaner as a is always a string, b is always an object (due to the use of the optional initialValue parameter in reduce)

    Edit 6 months later: Oh what was I thinking. "cleaner". I've angered the code Gods.

提交回复
热议问题