diff --git a/src/shared/objectToTableItems.ts b/src/shared/objectToTableItems.ts new file mode 100644 index 00000000..17d8a163 --- /dev/null +++ b/src/shared/objectToTableItems.ts @@ -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; +} diff --git a/tests/unit/objectArray.spec.ts b/tests/unit/objectArray.spec.ts new file mode 100644 index 00000000..e0a5fe25 --- /dev/null +++ b/tests/unit/objectArray.spec.ts @@ -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); + }); +});