Javascript - 如何通过参数过滤对象数组

时间:2016-02-07 18:54:34

标签: javascript arrays

我有一个变量,这是一个注释数组。

$scope.numOfCommentsCoupon

我想要的是一个变量,它是数组中具有特定值“couponId”的注释计数。

以下是评论模型

    var CommentSchema = new Schema({

    created: {
        type: Date,
        default: Date.now
    },
    couponId: {
        type: String,
        trim: true
    }

});

所以我需要过滤它,然后计算它,但我不知道如何。

3 个答案:

答案 0 :(得分:2)

如果你有一系列评论,那么你可以做这样的事情

var count = 0;
comments.filter(function(comment,index,array){
    if (comment.couponId === "some_value") {
        count++;
    }
});

或者您可以使用for循环迭代它。实现非常简单的东西

答案 1 :(得分:0)

我想我会按照您要做的事情进行操作,您可以使用array.filter

看起来像这样:

var currentCouponId = 1;
var matching = yourArray.filter(function (element) { return element.couponId == 1; });
console.log(matching.length);

答案 2 :(得分:0)

您可以在数组上使用reduce方法来获取couponId等于给定字符串的优惠券数量:

var comments = [
    {
        couponId : "1"
    },
    {
        couponId : "2"
    }
];

var couponIdToCount = "2";

var count = comments.reduce(function(previous, current) {
    return current.couponId == couponIdToCount ? previous + 1: previous;
}, 0);

console.log(count)