Is there any function in jQuery that is equivalent to PHP's array_column()?

前端 未结 6 1337
轻奢々
轻奢々 2021-02-10 04:57

What is the equivalent to PHP\'s array_column() in jQuery? I need the data inside the array without looping, in the same way as in PHP.

6条回答
  •  情话喂你
    2021-02-10 05:57

    var data = [];
    data.push({col1: 1, col2: 2});
    data.push({col1: 3, col2: 4});
    data.push({col1: 5, col2: 6});
    
    Array.prototype.getColumn = function(name) {
        return this.map(function(el) {
           // gets corresponding 'column'
           if (el.hasOwnProperty(name)) return el[name];
           // removes undefined values
        }).filter(function(el) { return typeof el != 'undefined'; }); 
    };
    
    console.log(data.getColumn('col1'));
    

    Result

    Array[3]
    0: 1
    1: 3
    2: 5
    

    It is possible to skip the .filter part just by taking the first element of array and checking if it has the corresponding key. But some rows might not have that key at all, while others might have it.

提交回复
热议问题