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)