javascriptphpjquery

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.


Solution

  • 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);