绕过多维数组
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
}
]
}
]
}
因此我需要一个包含动物元素的数组:
//result = [object1 -> name: Patrik, price: 135 ..], ..., [object3 -> name: Kesha, description: ...]
正如您在较低级别上看到的那样,如果参数 "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
到 return 是一个平面列表,以便循环的结果可以被 concat
合并。但是,在递归情况下,您不需要 return。
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)
我需要从复杂数组中获取一些数据到数组中。 例如我有这个结构:
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
}
]
}
]
}
因此我需要一个包含动物元素的数组: //result = [object1 -> name: Patrik, price: 135 ..], ..., [object3 -> name: Kesha, description: ...] 正如您在较低级别上看到的那样,如果参数 "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
到 return 是一个平面列表,以便循环的结果可以被 concat
合并。但是,在递归情况下,您不需要 return。
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)