下划线如何使用多个值过滤对象?

时间:2014-01-24 10:49:46

标签: underscore.js

我有一系列值:

var removeAge = ['7', '8', '5', '11'];

我希望过滤该对象,该对象的年龄属性不包含'removeAge'值

喜欢:

var array = [
    {'name':'one', "age":'3'},
    {'name':'two', "age":'1'},
    {'name':'three', "age":'3'},
    {'name':'four', "age":'1'},
    {'name':'one', "age":'7'},
    {'name':'one', "age":'5'},
    {'name':'one', "age":'7'},
    {'name':'one', "age":'8'},
    {'name':'one', "age":'7'},
    {'name':'one', "age":'11'},
    {'name':'one', "age":'7'}
]

如何删除包含“removeAge”中包含的年龄之一的对象?所以结果变成了像这样的对象:

var array = [
    {'name':'one', "age":'3'},
    {'name':'two', "age":'1'},
    {'name':'three', "age":'3'},
    {'name':'four', "age":'1'},
]

我试过这样,但没有结果:完全错了!

_.each(remove, function(val) {
    return _.filter(array, function(){
        return item.age != val
    })
} )

有人帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:4)

可以这样做:

_.reject(array, function(item){ return removeAge.indexOf(item['age']) != -1; });

答案 1 :(得分:1)

jQuery.map(removeAge, function (n, i) {
                    array = jQuery.grep(array, function (value) {
                        return value.age != n;
                    });

                });