Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 421
Sree Avatar asked Oct 26 '14 16:10

Sree


People also ask

What does array_ column do?

The array_column() function returns the values from a single column in the input array.

What is array_ column in PHP?

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.


1 Answers

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);
like image 107
fabpico Avatar answered Sep 20 '22 14:09

fabpico