Ho la seguente matrice JavaScript di oggetti immobiliari per la casa:
var json = {
'homes': [{
"home_id": "1",
"price": "925",
"sqft": "1100",
"num_of_beds": "2",
"num_of_baths": "2.0",
}, {
"home_id": "2",
"price": "1425",
"sqft": "1900",
"num_of_beds": "4",
"num_of_baths": "2.5",
},
// ... (more homes) ...
]
}
var xmlhttp = eval('(' + json + ')');
homes = xmlhttp.homes;
Quello che vorrei fare è essere in grado di eseguire un filtro sull'oggetto per restituire un sottoinsieme di oggetti "casa".
Per esempio, voglio essere in grado di filtrare in base a: prezzo
, sqft
, num_of_beds
, e num_of_baths
.
Come posso eseguire qualcosa in JavaScript come lo pseudo-codice qui sotto:
var newArray = homes.filter(
price <= 1000 &
sqft >= 500 &
num_of_beds >=2 &
num_of_baths >= 2.5 );
Nota, la sintassi non deve essere esattamente come sopra. Questo è solo un esempio.
Potete usare il metodo Array.prototype.filter
:
var newArray = homes.filter(function (el) {
return el.price <= 1000 &&
el.sqft >= 500 &&
el.num_of_beds >=2 &&
el.num_of_baths >= 2.5;
});
Esempio dal vivo:
var obj = {
'homes': [{
"home_id": "1",
"price": "925",
"sqft": "1100",
"num_of_beds": "2",
"num_of_baths": "2.0",
}, {
"home_id": "2",
"price": "1425",
"sqft": "1900",
"num_of_beds": "4",
"num_of_baths": "2.5",
},
// ... (more homes) ...
]
};
// (Note that because `price` and such are given as strings in your object,
// the below relies on the fact that <= and >= with a string and number
// will coerce the string to a number before comparing.)
var newArray = obj.homes.filter(function (el) {
return el.price <= 1000 &&
el.sqft >= 500 &&
el.num_of_beds >= 2 &&
el.num_of_baths >= 1.5; // Changed this so a home would match
});
console.log(newArray);
Questo metodo fa parte del nuovo standard ECMAScript 5th Edition, e può essere trovato su quasi tutti i browser moderni.
Per IE, puoi includere il seguente metodo per compatibilità:
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun /*, thisp*/) {
var len = this.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this) {
var val = this[i];
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
Puoi provare a usare un framework come jLinq - di seguito c'è un esempio di codice che usa jLinq
var results = jLinq.from(data.users)
.startsWith("first", "a")
.orEndsWith("y")
.orderBy("admin", "age")
.select();
Per maggiori informazioni puoi seguire il link http://www.hugoware.net/projects/jlinq
Potresti farlo abbastanza facilmente - ci sono probabilmente molte implementazioni tra cui puoi scegliere, ma questa è la mia idea di base (e probabilmente c'è qualche formato in cui puoi iterare su un oggetto con jQuery, solo che non mi viene in mente in questo momento):
function filter(collection, predicate)
{
var result = new Array();
var length = collection.length;
for(var j = 0; j < length; j++)
{
if(predicate(collection[j]) == true)
{
result.push(collection[j]);
}
}
return result;
}
E poi si potrebbe invocare questa funzione in questo modo:
filter(json, function(element)
{
if(element.price <= 1000 && element.sqft >= 500 && element.num_of_beds > 2 && element.num_of_baths > 2.5)
return true;
return false;
});
In questo modo, puoi invocare il filtro in base a qualsiasi predicato tu definisca, o anche filtrare più volte usando filtri più piccoli.