使用 _.where 和数组 underscore.js
using _.where with array underscore.js
我是新手 underscore.js
我有两个对象 TOWERS
和 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
}
]
我正在 selecting TOWERS
id 其中 project:1
使用:
var getTowers = _.where(TOWERS, {project:1});
var getUniqueTowers = _.chain(getTowers).pluck("id").unique().compact().value();
我得到了[1,2,3,4,5]
现在我想 select 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()
没有下划线的版本
var units = UNITS.filter(function (unit) {
return getUniqueTowers.indexOf(unit.tower) >= 0;
})
我是新手 underscore.js
我有两个对象 TOWERS
和 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
}
]
我正在 selecting TOWERS
id 其中 project:1
使用:
var getTowers = _.where(TOWERS, {project:1});
var getUniqueTowers = _.chain(getTowers).pluck("id").unique().compact().value();
我得到了[1,2,3,4,5]
现在我想 select 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()
没有下划线的版本
var units = UNITS.filter(function (unit) {
return getUniqueTowers.indexOf(unit.tower) >= 0;
})