使用_.其中array下划线.js

using _.where with array underscore.js

本文关键字:下划线 js array 其中 使用      更新时间:2023-09-26

我是新来的下划线。我有两个对象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]}  

您可以将.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;            
})