Perform .join on value in array of objects

前端 未结 10 1498
囚心锁ツ
囚心锁ツ 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.

    0 讨论(0)
  • 2020-11-29 15:55

    not sure, but all this answers tho they work but are not optiomal since the are performing two scans and you can perform this in a single scan. Even though O(2n) is considered O(n) is always better to have a true O(n).

    const Join = (arr, separator, prop) => {
        let combined = '';
        for (var i = 0; i < arr.length; i++) {
            combined = `${combined}${arr[i][prop]}`;
            if (i + 1 < arr.length)
                combined = `${combined}${separator} `;
        }
        return combined;
    }
    

    This might look like old school, but allows me to do thig like this:

    skuCombined = Join(option.SKUs, ',', 'SkuNum');
    
    0 讨论(0)
  • 2020-11-29 15:56

    On node or ES6+:

    users.map(u => u.name).join(', ')
    
    0 讨论(0)
  • 2020-11-29 15:58

    An old thread I know but still super relevant to anyone coming across this.

    Array.map has been suggested here which is an awesome method that I use all the time. Array.reduce was also mentioned...

    I would personally use an Array.reduce for this use case. Why? Despite the code being slightly less clean/clear. It is a much more efficient than piping the map function to a join.

    The reason for this is because Array.map has to loop over each element to return a new array with all of the names of the object in the array. Array.join then loops over the contents of array to perform the join.

    You can improve the readability of jackweirdys reduce answer by using template literals to get the code on to a single line. "Supported in all modern browsers too"

    // a one line answer to this question using modern JavaScript
    x.reduce((a, b) => `${a.name || a}, ${b.name}`);
    
    0 讨论(0)
  • 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(",")
    
    0 讨论(0)
  • 2020-11-29 16:00

    If object and dynamical keys: "applications\":{\"1\":\"Element1\",\"2\":\"Element2\"}

    Object.keys(myObject).map(function (key, index) {
        return myObject[key]
    }).join(', ')
    
    0 讨论(0)
提交回复
热议问题