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: "" },
|
{ 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 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: "" });
|
||||||
};
|
}
|
||||||
|
|
Loading…
Reference in a new issue