简体   繁体   English

使用_.where与数组underscore.js

[英]using _.where with array underscore.js

I am new to underscore.js 我是underscore.js的新手
I have two objects TOWERS and UNITS 我有两个对象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
    }
]  

I am selecting TOWERS id which has project:1 using: 我正在选择使用以下project:1 TOWERS ID

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

I got [1,2,3,4,5] 我得到了[1,2,3,4,5]
Now I want to select UNITS which tower's value is in [1,2,3,4,5] 现在,我要选择“塔”的值在[1,2,3,4,5] UNITS

Is there any way to use _.where like below? 有什么办法可以使用_.where如下所示?

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

You can use .filter with .indexOf , like so 您可以将.filter.indexOf .filter使用,就像这样

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

Example

Version without underscore 没有下划线的版本

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM