I have a array of objects
- Some objects have id and some are not
- those having id can present with either "split" or "relation" key not both
- inside split there can be another split or relation
- now I need to read all relation present by digging deeply
I need output like below:
let _rel = [
{"relation": "a"},
{"relation": "b"}
]
// my try which is not working
const getRelations = (arr, _rel=[]) => {
for(let {uuid, relations, split} of arr){
if(uuid) {
if(relations) [..._rel, relations]
else if(split) {
getRelations(split)
}
}
}
return _rel
}
getRelations(arr)
Input:
let arr = [
{"start_offset": 0},
{
"uuid": "100",
"relations": [
{
"relation": "a",
}
]
},
{"start_offset": 355},
{
"uuid": "200",
"split": [
{
"uuid": "300",
"split": [
{
"uuid": "400",
"relations": [
{
"relation": "b",
}
]
}
]
},
{
"uuid": "500",
}
],
},
{"start_offset": 689}
]
// my try which is not working
const getRelations = (arr, _rel=[]) => {
for(let {uuid, relations, split} of arr){
if(uuid) {
if(relations) [..._rel, relations]
else if(split) {
getRelations(split)
}
}
}
return _rel
}
getRelations(arr)
4
Answers
You need to assign the result of the spread operation to
_rel
when you haverelations
in order to accumulate the values.When you recursively call
getRelations(split)
, you should merge the results with_rel
.EDIT
Pure javascript (wrong react)
You can make sure the function works with arrays of any type by using a generic parameter
You could take a check and return a flat array of
relations
or an empty array.A couple of changes:
1- When you have relations, push the
{ "relation": relations }
object into the
_rel
array.2- When you have
split
, recursively callgetRelations
with the split array and pass the existing_rel
array.Now, the relations array should be correctly populated with the desired output.
An one-liner: