[英]Bypassing the multi-dimensional arrays
我需要從復雜數組中獲取一些數據。 例如,我有這個結構:
animals =
/*...*/
list: [
{
type: "fluffy"
withCategories: false
animal: [
{
name: "Patrik"
description: "..."
price: 135
weight: 220
rating: 94
}
{
name: "Mike"
description: "..."
price: 135
weight: 235
rating: 97
}
]
}
{
imageUrl: "/img/borsh.jpg"
type: "pets"
withCategories: true
categories: [
{
name: "parrot"
imageUrl: "/img/parrot.jpg"
withCategories: false
animal: [
{
name: "Kesha"
description: "..."
price: 75
weight: 250
rating: 89
}
]
}
]
}
結果,我需要一個包含動物元素的數組: //結果= [object1->名稱:Patrik,價格:135 ..],...,[object3->名稱:Kesha,描述:...]您可以在較低的級別看到如果參數“ withCategories” = true,我們將遞歸下降。 我試圖實現它:
PlacesService.getAllAnimals = ->
merged = []
temp = (getAnimalByCategory(category) for category in animals.list)
merged = merged.concat.apply(merged, temp)
return merged
getAnimalByCategory = (category) ->
if category.withCategories == false
return category.animal
else
(getAnimalByCategory(an) for an in category.categories)
但是出了點問題:(有人可以幫我嗎?我找不到任何錯誤。
您希望您的getAnimalByCategory
返回一個平面列表,以便可以由concat
合並循環的結果。 但是,在遞歸情況下,您不會返回此類。
PlacesService.getAllAnimals = ->
[].concat.apply([], getAnimalByCategory(category) for category in animals.list)
getAnimalByCategory = (category) ->
if not category.withCategories
category.animal
else
[].concat.apply([], getAnimalByCategory(an) for an in category.categories)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.