在javascript中过滤对象数组 [英] Filter an array of objects in javascript

查看:104
本文介绍了在javascript中过滤对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按属性值过滤JavaScript对象。这是一个场景:

I would like to filter JavaScript objects by their property value. Here is a scenario:

下面的数组是我正在使用的一个小例子

The array below is a small example of what I'm working with

 var array = [{

    "Title": "July 13 - July 19 2014",
    "displayAd_imp": "15,242,505",
    "Date": "2014-07-17T00:00:00.000Z",
    "WeekNo": 29
}, {

    "Title": "July 20 - July 26 2014",
    "displayAd_imp": "15,942,705",
    "Date": "2014-07-24T00:00:00.000Z",
    "WeekNo": 30
}, {

    "Title": "July 27 - Aug 2 2014",
    "displayAd_imp": "15,683,545",
    "Date": "2014-07-31T00:00:00.000Z",
    "WeekNo": 31
}, {

    "Title": "Aug 3 - Aug 9 2014",
    "displayAd_imp": "15,042,005",
    "Date": "2014-08-07T00:00:00.000Z",
    "WeekNo": 32
}, {

    "Title": "Aug 10 - Aug 17 2014",
    "displayAd_imp": "15,442,605",
    "Date": "2014-08-14T00:00:00.000Z",
    "WeekNo": 33
}]

在我的应用程序中,有两个下拉字段可供用户选择一周的范围。我正在通过日期计算周数并插入WeekNo作为属性。我想使用WeekNo来获取基于起始值的一大块数据。

In my app there are two dropdown fields that would let users pick a range of weeks. I'm calculating the week number by the "Date" and inserting the "WeekNo" as a property. I would like to use WeekNo to get a chunk of data based on the start-end values.

例如,如果开始日期是第29周,结束是第32周方法将返回相关数据。

Example would be if start date is week29 and end is week32 the method would return the relevant data.

我有一个 Jsfiddle 如果有人想要的话更新它。

I have a Jsfiddle going if someone would like to update it.

提前多谢!

推荐答案

您可以使用 Array.filter 功能。您可以直接在阵列上调用它,然后提供回调。如果该回调返回true,则该元素包含在从 filter 返回的新数组中。

You can use the Array.filter function. You call it directly on your array then provide a callback. If that callback returns true, the element is included in a new array that's returned from filter.

例如:

var newArr = array.filter(function(item) {
    return (item.WeekNo >= 29 && item.WeekNo < 32);
});

这是一个更新的JSfiddle ,其中包括。

这篇关于在javascript中过滤对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆