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.

30th Jun 2022, 1:47 PM
Prasanna watson
Prasanna watson - avatar
6 Antworten
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.
30th Jun 2022, 1:49 PM
Justice
Justice - avatar
0
I need only IDs from nested objects
30th Jun 2022, 1:58 PM
Prasanna watson
Prasanna watson - avatar
0
That's great. But where's your attempt and state any errors you may be getting.
30th Jun 2022, 1:59 PM
Justice
Justice - avatar
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
30th Jun 2022, 2:07 PM
Prasanna watson
Prasanna watson - avatar
0
The object in the snippet has structure flaw, it's unusable for testing.
30th Jun 2022, 2:37 PM
Ipang
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/
9th Nov 2022, 11:55 AM
Tanjore Raj
Tanjore Raj - avatar