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.
The array_column() function returns the values from a single column in the input array.
array_column() returns the values from a single column of the array , identified by the column_key . Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array.
You can do it with .map(). Immagine a fetch of database rows.
With arrow function
To have a reusable arrayColumn(array, column)
function:
const array = [
{id: 1, name: 'foo'},
{id: 2, name: 'bar'},
];
const arrayColumn = (array, column) => {
return array.map(item => item[column]);
};
const names = arrayColumn(array, 'name');
console.log(names);
Or you can use .map
directly:
const array = [
{id: 1, name: 'foo'},
{id: 2, name: 'bar'},
];
const names = array.map(item => item.name);
console.log(names);
Before ES6 (2015)
var array = [
{id: 1, name: 'foo'},
{id: 2, name: 'bar'},
];
function arrayColumn(array, columnName) {
return array.map(function(value,index) {
return value[columnName];
})
}
var names = arrayColumn(array, 'name');
console.log(names);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With