[
{
"id": "11ed-a261-0242ac120002",
"name": "Languages",
"code": 1,
"description": "Here you can find teacher for any language. Learn when you want and how you want.",
"childrenCategories": [
{
"id": "a261-0242ac120002",
"name": "German",
"code": 7,
"description": "Here you can find teacher for German. Learn when you want and how you want.",
"childrenCategories": []
},
{
"id": "a261-0242ac120002",
"name": "Spanish",
"code": 8,
"description": "Here you can find teacher for Spanish. Learn when you want and how you want.",
"childrenCategories": []
},
]
},
{
"id": "a261-0242ac120002",
"name": "Sciences",
"code": 3,
"description": "It is your online university. Learn whatever you want and become better.",
"childrenCategories": [
{
"id": "6a66915a-3439-11ed-a261-0242ac120002",
"name": "Mathematics",
"code": 12,
"description": "It is your online university. Learn Mathematics and become better.",
"childrenCategories": []
},
{
"id": "6a669420-3439-11ed-a261-0242ac120002",
"name": "Physics",
"code": 13,
"description": "It is your online university. Learn Physics and become better.",
"childrenCategories": []
},
]
},
]
I want to get such an array
[
{"name": "Languages", "code": 1},
{"name": "German", "code": 7},
{"name": "Spanish", "code": 8},
{"name": "Sciences", "code": 3},
{"name": "Mathematics", "code": 12},
{"name": "Physics", "code": 13,},
]
I have an array with nested objects and arrays that I want to recursively filter and return a new array without nesting that will only have the fields "name": "Languages" "code": 1,
I wrote the following code. He works. I want to know other options for solving this problem.
const flatten = (arr) => {
let result = []
arr.flatMap((item) => {
result.push({name: item.name, code: item.code})
item.childrenCategories.map(child =>
result.push({name: child.name, code: child.code})
)
})
return result
}
2
Answers
Here’s another way of solving this problem using recursion:
How about this?
This approach defines a recursive function
flattenRecursive
that iterates over each item in the array. If an item has children categories, the function recursively calls itself to flatten those categories as well. This way, you don’t need to rely on array methods likeflatMap
ormap
to flatten the nested structure.