返回基于父过滤器的Javascript子数组
免责声明:我了解一些Java,但对Javascript几乎一无所知,并且有大约2天的时间来解决其他人的问题,这只是其中的一小部分 我有一个嵌套数组。我知道店号,但只需要获得该店零件的阵列返回基于父过滤器的Javascript子数组,javascript,arrays,Javascript,Arrays,免责声明:我了解一些Java,但对Javascript几乎一无所知,并且有大约2天的时间来解决其他人的问题,这只是其中的一小部分 我有一个嵌套数组。我知道店号,但只需要获得该店零件的阵列 "shops": [ { "shopID": "15231", "city": "Anytown", "state": "MO"
"shops": [
{
"shopID": "15231",
"city": "Anytown",
"state": "MO",
"inventory": [
{
"description": "filter",
"partnumber": "MGL57047",
"shelf": "Z",
},
{
"description": "filter",
"partnumber": "84060",
"shelf": "A",
}
},
{
"shopID": "15232",
"city": "Springfield",
"state": "IL",
"inventory": [
{
"description": "filter",
"partnumber": "MGL57048",
"shelf": "B",
},
{
"description": "filter",
"partnumber": "84061",
"shelf": "A",
}
}
以下是我尝试过的:
const enteredShopID = '15231' // This isn't hard-coded in my app.
// Pull the list of all consumables for the current shop
var currentShop = application.data.shops.filter(s => s.shopID == enteredShopID)
这会给我一个包含商店和该商店所有库存的数组,但我需要一个库存数组。我试过了
var currentShop = application.data.shops.inventory.filter(s => s.shopID == enteredShopID)
但那没用。真的,我只是在这里摸索。有没有办法使后一条语句起作用,并以某种方式引用父项的shopID?只需在筛选后使用map()
var currentShop = application.data.shops
.filter(s => s.shopID == enteredShopID)[0]
// checking if the current shop is actually null because no shops matched the ID
var currentShopInventory = (currentShop || {}).inventory || []
或者使用find()
如果ID是唯一的,那么它应该是
.find()
,而不是.filter()
!第一个建议奏效了!
// Note: If you use find(), there's a chance that there is no matching object
// So you'll have to check for that before you access the "inventory" key
// Otherwise you'll get "Cannot access 'inventory' of null"
var matchingShop = application.data.shops
.find(s => s.shopID == enteredShopID)
// Doing the checking here using an "or" if the matchingShop is null
var currentShop = matchingShop || {}
var currentShopInventory = currentShop.inventory || []