Add object to Table Items helper function and specs

This commit is contained in:
Matthias 2023-10-24 19:21:39 +02:00
parent d8c65e87ef
commit aa2f791406
2 changed files with 52 additions and 0 deletions

View File

@ -0,0 +1,31 @@
interface childObjects {
[key: string]: any;
}
interface MutatingObject {
[key: string]: childObjects[];
}
/**
*
* @param originalobj Object in the form {Name, [{metric: value}]]}
* @param valueKey Key to use for result
* @returns Object in the form [{valueKey: metric, Name: value}]
*/
export function formatObjectForTable(originalobj: MutatingObject, valueKey: string) {
const result = Object.entries(originalobj).reduce((acc: childObjects[], [key, value]) => {
value.forEach((item) => {
const [metric, val] = Object.entries(item)[0];
const existingItem = acc.find((i) => i[valueKey] === metric);
if (existingItem) {
existingItem[key] = val;
} else {
acc.push({
[valueKey]: metric,
[key]: val,
});
}
});
return acc;
}, []);
return result;
}

View File

@ -0,0 +1,21 @@
import { describe, it, expect } from 'vitest';
import { formatObjectForTable } from '@/shared/objectArrayConvert';
describe('objectArray.ts', () => {
it('converts object array', () => {
const originalObj = {
XXX1: [{ Profit: 20 }, { Loss: 50 }],
XXX2: [{ Profit: 50 }, { Loss: 21 }],
};
const expected = [
{ metric: 'Profit', XXX1: 20, XXX2: 50 },
{ metric: 'Loss', XXX1: 50, XXX2: 21 },
];
const expected2 = [
{ settings: 'Profit', XXX1: 20, XXX2: 50 },
{ settings: 'Loss', XXX1: 50, XXX2: 21 },
];
expect(formatObjectForTable(originalObj, 'metric')).toEqual(expected);
expect(formatObjectForTable(originalObj, 'settings')).toEqual(expected2);
});
});