I have a nested object that is being returned from an API call in a React application whose structure is as follows:
{
"Toys":{
"Dolls":[
"yellow hair",
"black hair",
"red hair"
],
"Trucks":[
"green",
"red",
"blue"
]
},
"Sweets"{
"Gum":[
"Trident",
"Juicy Fruit"
],
"Candy":[
"Lollipop",
"Gummi bears"
]
}
}
I am not strong in React/Javascript and I am struggling to manipulate this. I have looked at other examples and in all those cases, they know the contents of the object and provide examples showing that the object can be manipulated like this: (assuming the object is called result) result.Toys.Dolls
to get the array ["yellow hair", "red hair", 'black hair']
.
Unfortunately, those solutions are not helping me. In my case, I do not know what is in the object so I cannot reference by name. The data is coming from a database so my solution need to handle whatever data the database query returns in that object. The only data points that I know are “Toys” and “Sweets” and even those are subject to change over time.
What I am trying to do is get the top level, second level, and third level values in individual arrays. So I want the end result to look like this.
array1 = ["Toys, "Sweets"]
then for Toys
array 2 = ["Dolls", "Trucks"]
then focusing on Dolls
array3 = ["yellow hair", "black hair", "red hair"]
then focusing on Trucks
array4= "green", "red", "blue"]
And then similar logic with Sweets, so that
array5 = ["Gum, "Candy"]
array6 = ["Trident", "Juicy Fruit"]
array7 = ["Lollipop", "Gummi bears"]
I have tried using map and get the error .map is not a function
. I have also tried reduce and filter and get a similar type of error.
I just don’t know how to extract what I need from this object. Could someone please provide some direction?
5