简体   繁体   中英

using _.where with array underscore.js

I am new to underscore.js
I have two objects TOWERS and UNITS

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:

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

I got [1,2,3,4,5]
Now I want to select UNITS which tower's value is in [1,2,3,4,5]

Is there any way to use _.where like below?

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

You can use .filter with .indexOf , like so

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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