Save duplicate attribute keys as array (#3055)
This commit is contained in:
parent
9ff8d83a43
commit
27b990944d
2 changed files with 29 additions and 12 deletions
|
@ -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"] });
|
||||
});
|
||||
});
|
||||
|
|
|
@ -1,20 +1,24 @@
|
|||
export type KeyValueType = { key: string; value: string };
|
||||
|
||||
export const keyValueToArray = (
|
||||
attributeArray: KeyValueType[] = []
|
||||
): Record<string, string[]> =>
|
||||
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<string, string[]> = {};
|
||||
|
||||
export const arrayToKeyValue = (
|
||||
attributes: Record<string, string[]> = {}
|
||||
): 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<string, string[]> = {}) {
|
||||
const result = Object.entries(attributes).flatMap(([key, value]) =>
|
||||
value.map<KeyValueType>((value) => ({ key, value }))
|
||||
);
|
||||
|
||||
return result.concat({ key: "", value: "" });
|
||||
};
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue