Get object of an array by providing an attribute of the object

6

I have an array of objects like the following:

var nicknames = []

nicknames.push( {id:"100", name:"Juan"} , {id:"200", name:"Mateo"} );

How can I get the data of one of the objects in the nicknames array by supplying the name or the ID of that object?


Original question: Javascript get corresponding key / value from object

    
asked by tomloprod 06.12.2015 в 09:28
source

4 answers

9

There is a very simple solution for that, it is the filter method available natively in all arrays Reference in the MDN :

var results = nicknames.filter(function (nickname) { return nickname.id == '200'; });
var firstObj = (results.length > 0) ? results[0] : null;

Note:

The filter method returns an array with all of the elements for which the condition is fulfilled, with which it is necessary to contemplate that the element does not exist or that there are several.

    
answered by 06.12.2015 / 13:02
source
6

Taking into account that we have the variable in the following way:

var nicknames= [
    {id:"100", nickname:"Juan"},
    {id:"200", nickname:"Mateo"}
];

Solution 1 - Native Js

Through the use Array.prototype.filter :

/**
 * Devolverá un arreglo con el objeto a buscar o uno vacio si no lo encuentra.
 */
var nickname = nicknames.filter(function(nickname) {
    return nickname.id === "100";
});

Through the use Array.prototype.reduce :

/**
 * Devolverá el arreglo requerido o null si no lo encuentra.
 */
var nickname = nicknames.reduce(function(value, nickname) {
    return nickname.id === "100" ? nickname : null;
}, null);

Solution 2 - Use of prototype

Another method is and which I like a lot, is the use of prototype. There would be something like the following:

/**
 * Devolverá el objeto que coincida con la llave-valor indicados como
 * argumentos de la función.
 *
 * @param String column    El nombre de la columna o llave de referencia
 * @param Any value        El valor buscado sobre la columna indicada
 * @return [Object|Null]   Devolverá null en caso de no hallar coincidencia, en caso contrario devolverá el objeto coincidente
 */
Array.prototype.findBy = function (column, value) {
    for (var i=0; i<this.length; i++) {
        var object = this[i];
        if (column in object && object[column] === value) {
            return object;
        }
    }

    return null;
}

The example of use would be as follows:

var nickname = nicknames.findBy('id', '100');

Solution 3 - Use of libraries

You can use a library like Underscore.js to give you tools like that for data filtering. Example:

var nickname = _.findWhere(nicknames, {id: "100"});

Official documentation of _.findeWhere () (in English)

    
answered by 13.09.2016 в 00:30
4

ECMAScript 2015 (ES6) provides the function find ()

Example of use:

function buscar_item_por_id(id){

    return items.find(function(item){
        return item.id === id;
    });

}
    
answered by 15.12.2015 в 19:58
1

As already mentioned Jorge Pastrano the easiest and most native way to make a selection about the arrangement is using the function filter :

var resultados = nicknames.filter(function (nickname) {
    //return {expresion booleana},
});

Where {expresión booleana} can be a comparison with property id or name as needed

resultados is assigned with a new fix only with filtered objects.

However, for browsers that do not support this function (for example IE8 or less) the following polyfill can be used (extracted from the documentation of filter )

if (!Array.prototype.filter) {
    Array.prototype.filter = function(fun/*, thisArg*/) {
        'use strict';

        if (this === void 0 || this === null) {
            throw new TypeError();
        }

        var t = Object(this);
        var len = t.length >>> 0;
        if (typeof fun !== 'function') {
            throw new TypeError();
        }

        var res = [];
        var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
        for (var i = 0; i < len; i++) {
            if (i in t) {
                var val = t[i];

                // NOTE: Technically this should Object.defineProperty at
                //       the next index, as push can be affected by
                //       properties on Object.prototype and Array.prototype.
                //       But that method's new, and collisions should be
                //       rare, so use the more-compatible alternative.
                if (fun.call(thisArg, val, i, t)) {
                    res.push(val);
                }
            }
        }

        return res;
    };
}
    
answered by 15.12.2015 в 19:49