I developed a JavaScript function that can merge multiple arrays into an array of objects based on provided key names. Here’s an example:
const mergeArraysToSeries = (arrs, keys) => {
const merged = [];
for (let dataIndex = 0; dataIndex < arrs[0].length; dataIndex++) {
const el = keys.reduce((combined, currKey, keyIndex) => {
const val = arrs[keyIndex][dataIndex];
return { ...combined, [currKey]: val };
}, {});
merged.push(el);
}
return merged;
}
const example = mergeArraysToSeries([[1,2,3], ['a','b','c']], ['num', 'letter'])
// example = [{num: 1, letter: 'a'}, {num: 2, letter: 'b'}, {num: 3, letter: 'c'}]
I am now looking to enhance this function with TypeScript to achieve autocomplete on the merged array and ensure type safety for each key. Is there a way to accomplish this without relying on any
types?
The current type signature I have is:
const mergeArrayToSeries = <K>(arrs: any[][], keys: (keyof K)[]): Record<keyof K, any>[] => ...
I would like to eliminate the usage of any
for passed arrays while maintaining type safety. Any suggestions on how to achieve this?
Thank you!
Edit: The goal is to make this work seamlessly for merging any number of arrays together.