0
Only get IDs from nested object of array using recursive functions?
Input: var treeData= { id: '1', name: 'er', children: [{ id: '2', name: 'es', children: [{ id: '3', name: 'es', [{ id: '4', }] }] }] } OUTPUT: ["1","2","3","4"] NOTE: Should be done using a recursive or any other simple way to achieve this. function.
6 Respuestas
0
What is your question, because the sentence with a question mark is more like a statement.
If you need any help, please show your attempt and be specific about what you are not understanding.
0
I need only IDs from nested objects
0
That's great. But where's your attempt and state any errors you may be getting.
0
I can use four for loops to get ids from each object, but in future another object will added into same object.
const ids = [];
JSON.stringify(treeData, (key, value) => {
if (key === "id") ids.push(value);
return value;
});
console.log(ids);
This will works but I need to achieve this using recursive functions
0
The object in the snippet has structure flaw, it's unusable for testing.
0
You can use Generator functions to solve this:
function* get_id(d){
yield* ('id' in d ? [d.id] : [])
for (var c of ('children' in d ? d.children : [])){
yield* get_uid(c)
}
}
let obj = {'id': '1','name': 'er',
'children': [{'id': '2','name': 'es',
'children': [{'id': '3','name': 'es','children':[{'id':'4'},{'id':'5'}]
}]
}]
}
var result = [...get_id(obj)]
console.log(result);
Working Link: https://jsfiddle.net/Lwpyasxu/