I’ am a begginer with Javascript and I am currently try to find all possible paths of a returned JSON object from an axios GET request.Every item can belong to one or more groups, and one group can belong to an other group.
e.g.
{
"name": "item1",
"groupNames": [ "GROUPA" ]
}
{
"name": "GROUPA",
"groupNames": [
"GROUPB"
]
}
....
{
name: "GROUPZ"
"groupNames": [
]
}
My issue is that my code is working only if a item name has only one parent groupName in the array.
What if we have more than one parentgroupNames? e.g
{
"name": "item1",
"groupNames": [ "GROUPA","GROUC",GROUBD ]
}
...
My current code:
let parent = 'item1';
do{
let endpoint = ${process.env.OPENHAB_HOST}:${process.env.OPENHAB_PORT}/rest/items/${parent}?recursive=false
result = await getAxiosRequest(endpoint,{},res); // get request to specific endpoint
parent = result.data.groupNames; }
while(result.data.groupNames.length !== 0 )
2
Answers
To find all the parent groups for an item that has multiple parent groups, you can modify your code as follows:
Initialize an array called parents to store the parent groups that you find.
In the loop, instead of assigning parent to result.data.groupNames, iterate over result.data.groupNames and add each group to the parents array.
After the loop, parents will contain all the parent groups for the given item.
Here’s how the modified code would look:
This should work even if the item has multiple parent groups.
It is not entirely clear what the end result should be after the loop has ran, but I’ll assume you would maybe collect the paths from the given item in an array.
As indeed you can get multiple groups, you need to either store them in a queue/stack for later processing, or use recursion (for the same reason).
Here is how it could look with recursion: