I wrote a function which gets data of generic object and properties(keys) which values should be returned:
resultToArray<T>(
data: T[],
prop: (keyof T | ((row: T) => string))[] = []
): string[][] {
// data: [{id: 1, name: 'first'}, {id: 2, name: 'second'}] -> [[1, 'first'], [2, 'second']]
// prop: ['id', 'name']
if (prop.length === 0) {
return data.map(Object.values);
} else {
const output = data.map(d => {
const a: string[] = [];
for (let i = 0; i < prop.length; i++) {
a.push(d[prop[i]])
}
return a;
});
return output
}
}
Example Input:
data -
[
{ name: 'Name', address: 'Address', branch: { locale: 'Locale' } },
{ name: 'Name2', address: 'Address2', branch: { locale: 'Locale2' } }
]
prop - [ 'name', (d) => d.branch.locale ]
Output should be [['Name', 'Locale'], ['Name2', 'Locale2']]
Function works fine for simple keys, but for nested keys is not working