Ho un array:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]
Non riesco a cambiare la struttura dell'array. Mi viene passato un id di 45
, e voglio ottenere 'bar'
per quell'oggetto nell'array.
Come posso farlo in JavaScript o usando jQuery?
Penso che il modo più semplice sarebbe il seguente, ma non funzionerà su Internet Explorer 8 (o precedente):
var result = myArray.filter(function(v) {
return v.id === '45'; // Filter out the appropriate one
})[0].foo; // Get result and access the foo property
Iterare su qualsiasi elemento dell'array. Per ogni elemento visitato, controlla l'id di quell'elemento. Se corrisponde, lo restituisce.
Se volete solo il codice:
function getId(array, id) {
for (var i = 0, len = array.length; i < len; i++) {
if (array[i].id === id) {
return array[i];
}
}
return null; // Nothing found
}
E la stessa cosa usando i metodi Array di ECMAScript 5:
function getId(array, id) {
var obj = array.filter(function (val) {
return val.id === id;
});
// Filter returns an array, and we just want the matching item.
return obj[0];
}