Last active
November 26, 2019 21:43
-
-
Save zdrr/49ab7b4587a8f70952e247c44479ecbc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface IDocument { | |
id: number; | |
documents: IDocument[]; | |
} | |
const DOCUMENTS: IDocument[] = [{ | |
id: 100, | |
documents: [ | |
{ | |
id: 1, | |
documents: [ | |
{ | |
id: 2, | |
documents: [ | |
{ | |
id: 3, | |
documents: [ | |
{ | |
id: 11, | |
documents: [ | |
{ | |
id: 12, | |
documents: [ | |
{ | |
id: 13, | |
documents: [ | |
{ | |
id: 14, | |
documents: [ | |
{ | |
id: 15, | |
documents: [ | |
{ | |
id: 16, | |
documents: [] | |
} | |
] | |
} | |
] | |
} | |
] | |
} | |
] | |
} | |
] | |
} | |
] | |
}, | |
{ | |
id: 4, | |
documents: [] | |
} | |
] | |
} | |
] | |
}, | |
{ | |
id: 5, | |
documents: [ | |
{ | |
id: 6, | |
documents: [] | |
} | |
] | |
} | |
] | |
}, { | |
id: 200, | |
documents: [ | |
{ | |
id: 7, | |
documents: [ | |
{ | |
id: 8, | |
documents: [{ | |
id: 9, | |
documents: [] | |
}] | |
} | |
] | |
}, | |
{ | |
id: 10, | |
documents: [] | |
} | |
] | |
}] | |
const flatDeep = <T>(items: T[], key: string) => { | |
const innerFlat = (item: T, arr = []): T[] => | |
arr.concat(item, ...(item[key] && item[key].length > 0 ? item[key].map(d => innerFlat(d)) : [])); | |
return items.map(d => innerFlat(d)).reduce((acc, curr) => [...acc, ...curr]); | |
}; | |
const flattenedIds = flatDeep<IDocument>(DOCUMENTS, 'documents').map(({ id }) => id); | |
console.log(flattenedIds); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment