[英]Return Javascript child array based on parent filter
免責聲明:我知道一些 Java 但幾乎沒有關於 Javascript 並且有大約 2 天的時間來解決別人的問題,其中這是一小部分。
我有一個嵌套數組。 我知道商店編號,但只需要獲取該商店中的零件數組。
"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()
// 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 || []
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.