Save duplicate attribute keys as array (#3055)

This commit is contained in:
Erik Jan de Wit 2022-08-05 15:47:30 +02:00 committed by GitHub
parent 9ff8d83a43
commit 27b990944d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 12 deletions

View file

@ -66,4 +66,17 @@ describe("Tests the convert functions for attribute input", () => {
{ key: "", value: "" }, { 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"] });
});
}); });

View file

@ -1,20 +1,24 @@
export type KeyValueType = { key: string; value: string }; export type KeyValueType = { key: string; value: string };
export const keyValueToArray = ( export function keyValueToArray(attributeArray: KeyValueType[] = []) {
attributeArray: KeyValueType[] = [] const validAttributes = attributeArray.filter(({ key }) => key !== "");
): Record<string, string[]> => const result: Record<string, string[]> = {};
Object.fromEntries(
attributeArray
.filter(({ key }) => key !== "")
.map(({ key, value }) => [key, [value]])
);
export const arrayToKeyValue = ( for (const { key, value } of validAttributes) {
attributes: Record<string, string[]> = {} if (key in result) {
): KeyValueType[] => { result[key].push(value);
} else {
result[key] = [value];
}
}
return result;
}
export function arrayToKeyValue(attributes: Record<string, string[]> = {}) {
const result = Object.entries(attributes).flatMap(([key, value]) => const result = Object.entries(attributes).flatMap(([key, value]) =>
value.map<KeyValueType>((value) => ({ key, value })) value.map<KeyValueType>((value) => ({ key, value }))
); );
return result.concat({ key: "", value: "" }); return result.concat({ key: "", value: "" });
}; }