diff --git a/src/components/key-value-form/key-value-convert.test.ts b/src/components/key-value-form/key-value-convert.test.ts index 7a81c6cdea..36edb14101 100644 --- a/src/components/key-value-form/key-value-convert.test.ts +++ b/src/components/key-value-form/key-value-convert.test.ts @@ -66,4 +66,17 @@ describe("Tests the convert functions for attribute input", () => { { key: "", value: "" }, ]); }); + + it("convert duplicates into array values", () => { + const given = [ + { key: "theKey", value: "one" }, + { key: "theKey", value: "two" }, + ]; + + //when + const result = keyValueToArray(given); + + //then + expect(result).toEqual({ theKey: ["one", "two"] }); + }); }); diff --git a/src/components/key-value-form/key-value-convert.ts b/src/components/key-value-form/key-value-convert.ts index abb7c916e4..1e8437dd65 100644 --- a/src/components/key-value-form/key-value-convert.ts +++ b/src/components/key-value-form/key-value-convert.ts @@ -1,20 +1,24 @@ export type KeyValueType = { key: string; value: string }; -export const keyValueToArray = ( - attributeArray: KeyValueType[] = [] -): Record => - Object.fromEntries( - attributeArray - .filter(({ key }) => key !== "") - .map(({ key, value }) => [key, [value]]) - ); +export function keyValueToArray(attributeArray: KeyValueType[] = []) { + const validAttributes = attributeArray.filter(({ key }) => key !== ""); + const result: Record = {}; -export const arrayToKeyValue = ( - attributes: Record = {} -): KeyValueType[] => { + for (const { key, value } of validAttributes) { + if (key in result) { + result[key].push(value); + } else { + result[key] = [value]; + } + } + + return result; +} + +export function arrayToKeyValue(attributes: Record = {}) { const result = Object.entries(attributes).flatMap(([key, value]) => value.map((value) => ({ key, value })) ); return result.concat({ key: "", value: "" }); -}; +}