'function working with local data but not with database data
so here is the function
const array = [
{
name:'level1',
id:1,
parent_id:null
},
{
name:'level2',
id:2,
parent_id:1
},
{
name:'level3',
id:3,
parent_id:2
},
]
function recurse (array,givenId){
let node = []
array
.filter(function (d){return d.id === givenId})
.forEach(function (d){
let cd = d
cd.parent = recurse(array,d.parent_id)
return node.push(cd)
})
return node
}
const result = recurse(array,3)
this function works well with the data here log of recurse function
but if i go fetch on my database (localhost) the data are written the same way (id,name,parent_id)
for reasons i cannot use the filter()
here is my function to fetch :
async function getCategories(){
let req = await fetch('http://localhost/crud/getcattest.php')
let res = await req.json()
return res.result
}
which return this json : Screen shot of console after getCategories().then(cat=>{console.log(cat)})
so i have tried (see below) to insert into an array then return the array thinking maybe since it is async at the call of the function maybe i had an issue (inside the first then()) so i stored the datas in an array then returned it chaining this return with another then(), the array is their so no issue here
getCategories().then(item=>{
let arr= []
arr.push(item)
return arr
}).then(retArray=>{
recurse(retArray,*anyId*)
})
so i have tried recurse with retArray[0] it is the same i had wrote some console log before and inside the filter function and before the return node and we never pass the check on the filter going straight to the end
so i hope i was clear enough (English is not my native language)
just ask if you need more information
Thanks in advance
Solution 1:[1]
May be problem lies in the code. Please try below
getCategories().then(items => {
/// please check if items is array.
/// or else items.result might be array. depends on response of the code.
recurse(items, *anyId*)
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shriram Jadhav |
