Potresti implementare una funzione del genere
codice:
function where(array, query, andLogic = 1) {
if (!(andLogic in [0, 1])) {
andLogic = 1;
}
return array.filter(function(o) {
var res = andLogic;
Object.keys(query).forEach(function(par) {
var resPar = o[par] === query[par];
res = (!!andLogic)? (res && resPar) : (res || resPar);
});
return res;
});
};
La funzione filtra gli elementi dell'array se la funzione di callback ritorna true
e questo è possibile solo se ciascuno (o almeno uno) dei parametri della query corrisponde al valore dell'array. Il 'ciascuno' (and) o 'almeno uno' (or) è un comportamento che puoi controllare con un terzo parametro opzionale che di default è impostato a 'and'
Per fare i test ho usato il seguente oggetto (senza annidamenti)
codice:
var o = [
{ nome : "Alessandro",
eta : 42,
sesso : "M"
},
{ nome : "Bruno",
eta : 55,
sesso : "M"
},
{ nome : "Cristina",
eta : 50,
sesso : "F"
},
{ nome : "Diana",
eta : 48,
sesso : "F"
},
{ nome : "Enrico",
eta : 50,
sesso : "M"
}
];
E questi sono i test che ho eseguito
codice:
/* =========== TEST =========== */
console.info("> Inizio Test <")
console.log(where(o, { eta: 55 }));
// Ritorna un array con un solo oggetto
console.log(where(o, { nome: "Alessandro" }));
// Ritorna un array con un solo oggetto
console.log(where(o, { sesso: "M" }));
// Ritorna un array con 3 oggetti
console.log(where(o, { eta: 52 }));
// Ritorna un array vuoto
console.log(where(o, { eta: 50, sesso: "F" }));
// Ritorna un array con un solo oggetto (logica AND per default)
console.log(where(o, { eta: 10, sesso: "M" }, 'foobar'));
// Ritorna un array vuoto (logica AND per default, 'foobar' non valido)
console.log(where(o, { eta: 50, sesso: "X" }, 0));
// Ritorna un array con 2 oggetti (logica OR)
console.log(where(o, { chiaveinesistente: '0' }));
// Ritorna un array vuoto se la chiave non esiste
console.log(where(o, { chiaveinesistente: '0', nome: 'Bruno' }, 0));
// Ritorna un array con un solo elemento (logica OR)
console.log(where(o, { nome: 'valoreinesistente' }));
// Ritorna un array vuoto se il valore non esiste
Esempio funzionante (testato su Chrome)
http://codepen.io/anon/pen/xRwoez?editors=0010