簡體   English   中英

使用_.where與數組underscore.js

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

我是underscore.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
    }
]  

我正在選擇使用以下project:1 TOWERS ID

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

我得到了[1,2,3,4,5]
現在,我要選擇“塔”的值在[1,2,3,4,5] UNITS

有什么辦法可以使用_.where如下所示?

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

您可以將.filter.indexOf .filter使用,就像這樣

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;            
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM