计算对象的出现次数

时间:2014-08-13 13:38:47

标签: javascript jquery underscore.js

我正在努力让用户预览他们在表单中所做的更改,我在表单中比较了更改前后表单字段中的序列化对象数组。这一切都运行正常,但我需要排除有很多的'product [territory_ids] []'元素,因为我不需要这么深的比较。下面的代码工作正常。

// Get product form values before any changes are made
// and serialise them into an array of objects
$(".product_form_edit").ready(function() {
    form_before = $(".product_form_edit").serializeArray()

    // Using Underscore JS take out all off the product[territory_ids][] elements
    // as they cause comparison to fail. 
    // We'll do a count comparision of the number of territories set separately 
    $.each(form_before, function(i){
        form_before = _.without(form_before, _.findWhere(form_before, {name: 'product[territory_ids][]'}));
    });

    console.log(form_before);

});

我需要做的事情和我正在努力的是检测被检查的'product [territory_ids] []'元素数量的变化。

我想到了某种变化:

$.each(form_before, function(i){
    form_before = _.without(form_before, _.findWhere(form_before, {name: 'product[territory_ids][]'}));
});

像:

$.each(form_before, function(i){
   _.countBy(form_before, _.findWhere(form_before, {name: 'product[territory_ids][]'}));
}).length;

可能会工作,但是这很多其他尝试都会返回undefined。

有人可以帮忙吗?我确信它比我制作它简单。

1 个答案:

答案 0 :(得分:0)

好的,所以,在with an example I came up with稍微搞乱之后,我得出的结论是你可能想要使用_.filter来获取你的数组复选框。 filter将始终返回一个数组,因此如果没有选中复选框,则应该得到0。

$('#serialize').click(function() {
    var data = $('#testForm').serializeArray(),
        checkboxes = _.filter(data, function(i) {
            return i.name === 'xyz';
        });

    console.log(data, checkboxes);
    console.log(data.length, checkboxes.length);
});