根据属性过滤对象数组:指南
P粉087951442
P粉087951442 2023-10-09 16:41:54
0
2
617

我有以下房地产家庭对象的 JavaScript 数组:

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;

我想做的是能够对对象执行过滤器以返回“home”对象的子集。

例如,我希望能够基于以下内容进行过滤:pricesqftnum_of_bedsnum_of_baths

如何在 JavaScript 中执行类似下面的伪代码的操作:

var newArray = homes.filter( price <= 1000 & sqft >= 500 & num_of_beds >=2 & num_of_baths >= 2.5 );

请注意,语法不必与上面完全相同。这只是一个例子。

P粉087951442
P粉087951442

全部回复 (2)
P粉366946380

我很惊讶没有人发布一行回复:

const filteredHomes = json.homes.filter(x => x.price = 500 && x.num_of_beds >=2 && x.num_of_baths >= 2.5);

...只是为了让您可以更轻松地阅读:

const filteredHomes = json.homes.filter( x => x.price = 500 && x.num_of_beds >=2 && x.num_of_baths >= 2.5 );
    P粉315680565

    您可以使用数组.prototype.filter方法:

    var newArray = homes.filter(function (el) { return el.price = 500 && el.num_of_beds >=2 && el.num_of_baths >= 2.5; });

    实例:

    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 = with a string and number // will coerce the string to a number before comparing.) var newArray = obj.homes.filter(function (el) { return el.price = 500 && el.num_of_beds >= 2 && el.num_of_baths >= 1.5; // Changed this so a home would match }); console.log(newArray);
      最新下载
      更多>
      网站特效
      网站源码
      网站素材
      前端模板
      关于我们 免责声明 Sitemap
      PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!