복잡한 배열에서 배열로 데이터를 가져와야합니다. 예를 들어 다음과 같은 구조가 있습니다.
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 : ...] As 하위 레벨에서 "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)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다