栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JavaScript如何根据属性过滤对象数组?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaScript如何根据属性过滤对象数组?

您可以使用以下

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;});

现场示例:

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);

此方法是新ECMAscript 5th Edition标准的一部分,几乎可以在所有现代浏览器中找到。

对于IE,您可以包括以下兼容性方法:

if (!Array.prototype.filter) {  Array.prototype.filter = function(fun ) {    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;  };}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/379766.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号