I have an array of object which inturn has multiple array of object inside, the subGroups can be up to nth level and I want to flatten it to single array of object.
Input
obj = [{ id: a1, name: "apple", subGroups: [{id: a2, name: "apple-a", subGroups: {id: a3, name: "apple-b", subGroups: [{id: a4, name: "apple-c", subGroups: {id: a5, name: "apple-d", subGroups:[]}}]}}]}]
Expected output
[{ id: a1, name: "apple"}, {id: a2, name: "apple-a"}, {id: a3, name: "apple-b"}, {id: a4, name: "apple-c"},{id: a5, name: "apple-d"}]
I have used flat map and reduce but I'm only able to flatten upto second level. pls help
const arr = obj.reduce(
(arr, elem) => [...arr, ...elem.subGroups], []
)
console.log(arr)