Rumah > Soal Jawab > teks badan
Saya mempunyai susunan JavaScript objek rumah hartanah berikut:
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;
Apa yang saya mahu lakukan ialah dapat melakukan penapisan pada objek untuk mengembalikan subset objek "rumah".
Sebagai contoh, saya ingin dapat menapis berdasarkan: price
、sqft
、num_of_beds
和 num_of_baths
.
Bagaimana untuk melakukan sesuatu seperti pseudokod berikut dalam JavaScript:
var newArray = homes.filter( price <= 1000 & sqft >= 500 & num_of_beds >=2 & num_of_baths >= 2.5 );
Sila ambil perhatian bahawa sintaks tidak semestinya sama seperti di atas. Ini hanya contoh.
P粉3669463802023-10-10 10:39:56
Saya terkejut tiada siapa yang menghantar balasan satu baris:
const filteredHomes = json.homes.filter(x => x.price <= 1000 && x.sqft >= 500 && x.num_of_beds >=2 && x.num_of_baths >= 2.5);
...sekadar untuk memudahkan anda membaca:
const filteredHomes = json.homes.filter( x => x.price <= 1000 && x.sqft >= 500 && x.num_of_beds >=2 && x.num_of_baths >= 2.5 );
P粉3156805652023-10-10 00:41:14
Anda boleh menggunakan kaedah 数组.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; });
Contoh:
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);