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.
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.