使用_.where with array underscore.js

时间:2015-10-12 13:11:49

标签: javascript underscore.js

我是下划线的新手.js
我有两个对象TOWERSUNITS

var TOWERS = [
    {
        id: 1,
        name: "A",
        project: 1,
        floors: 8
    },
    {
        id: 2,
        name: "B",
        project: 1,
        floors: 8   
    },
    {
        id: 3,
        name: "C",
        project: 1,
        floors: 8   
    },
    {
        id: 4,
        name: "D",
        project: 1,
        floors: 8   
    },
    {
        id: 5,
        name: "E",
        project: 1,
        floors: 8   
    },
    {
        id: 6,
        name: "F",
        project: 2,
        floors: 8   
    },
    {
        id: 7,
        name: "G",
        project: 2,
        floors: 8   
    },
    {
        id: 8,
        name: "H",
        project: 2,
        floors: 8   
    }
]

var UNITS = [
    {
        id: 1,
        name: "101",
        unittype: 1,
        tower: 1,
        floor: 1
    },
    {
        id: 2,
        name: "102",
        unittype: 2,
        tower: 1,
        floor: 1
    },
    {
        id: 3,
        name: "101",
        unittype: 1,
        tower: 2,
        floor: 1
    },
    {
        id: 4,
        name: "102",
        unittype: 2,
        tower: 2,
        floor: 1
    },
    {
        id: 5,
        name: "101",
        unittype: 3,
        tower: 3,
        floor: 1
    },
    {
        id: 1,
        name: "102",
        unittype: 3,
        tower: 8,
        floor: 1
    }
]  

我选择TOWERS id project:1使用:

var getTowers = _.where(TOWERS, {project:1});
var getUniqueTowers = _.chain(getTowers).pluck("id").unique().compact().value();  

我得到[1,2,3,4,5]
现在,我想选择UNITS哪个塔的值在[1,2,3,4,5]

有没有办法像下面这样使用_.where

_.where(UNITS, {tower:[1,2,3,4,5]}  

1 个答案:

答案 0 :(得分:1)

您可以将.filter.indexOf一起使用,就像这样

var units = _.chain(UNITS)
    .filter(function (unit) {
        return _.indexOf(getUniqueTowers, unit.tower) >= 0;         
    })
    .value()

Example

没有下划线的版本

var units = UNITS.filter(function (unit) {
    return getUniqueTowers.indexOf(unit.tower) >= 0;            
})