There is a nested object array and I have to get all unique refIds, which are existing at any level.
I tried to iterate with for-loops, but it really gets very complicated. And also I don’t know how deep the data exactly is.
But is always an "type": "text"
element with an optional "marks"
field.
[
{
"type": "bulletList",
"content": [
{
"type": "listItem",
"content": [
{
"type": "paragraph",
"content": [
{
"type": "text",
"marks": [ // optional mark
{ "type": "refId", "attrs": { "refIds": [123, 234] } } // need this values
],
"text": "Item 1"
}
]
}
]
},
{
"type": "listItem",
"content": [
{
"type": "paragraph",
"content": [
{
"type": "text",
"marks": [{ "type": "refId", "attrs": { "refIds": [987] } }],
"text": "Item 2"
}
]
}
]
},
{
"type": "listItem",
"content": [
{
"type": "paragraph",
"content": [{ "type": "text", "text": "Item 3" }] // has no mark
},
{
"type": "bulletList", // example for nested child
"content": [
{
"type": "listItem",
"content": [
{
"type": "paragraph",
"content": [
{
"type": "text",
"marks": [
{ "type": "refId", "attrs": { "refIds": [876] } }
],
"text": "Sub 1"
}
]
}
]
}
]
}
]
}
]
}
]
Output should be
["123", "234", "987"]
3
Answers
Just walk recursively for arrays and objects and collect the ids into a set:
}
Assuming that missing
876
from the output was a mistake, you can use.flatMap()
on your array. For each object that you map you can check if its type istext
, and if it is, look for amarks
array that you then perform a nestedflatMap
on to transform into an array of ids. Since this inner.flatMap()
is done in a parent.flatMap()
the inner array results will be flattened/concatenated into the resulting array that’s eventually returned by the parent.flatMap()
(avoiding nested arrays). Otherwise, if the current object isn’t oftype
text
, then you can perform a recursive call, passing in thecontent
of the current object back into thegetRefIds()
function to get the refIds from that nested array (we defaultcontent
to an empty array if it doesn’t exist, which gets ignored when eventually flattened/merged into the resulting array). Finally, you can convert the result into aSet
and then back into an array to deduplicate:If your data is large, then you might want to avoid creating intermediate arrays (as done in the above example with each recursive call by the
.flatMap
s), and so you can try and use a nested recursive function like below to help: