Convert single array values to values (#2506)

This commit is contained in:
Erik Jan de Wit 2022-04-27 17:32:47 +02:00 committed by GitHub
parent 593d061224
commit 4349f19e24
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 1 deletions

View file

@ -111,4 +111,20 @@ describe("Tests the form convert util functions", () => {
attributes: {},
});
});
it("convert single element arrays to string", () => {
const given = {
config: { group: ["one"], another: { nested: ["value"] } },
};
const setValue = jest.fn();
//when
convertToFormValues(given, setValue);
//then
expect(setValue).toHaveBeenCalledWith("config", {
group: "one",
another: { nested: "value" },
});
});
});

View file

@ -89,7 +89,15 @@ export const convertToFormValues = (
if (key === "attributes" && isAttributesObject(value)) {
setValue(key, arrayToKeyValue(value as Record<string, string[]>));
} else if (key === "config" || key === "attributes") {
setValue(key, !isEmpty(value) ? unflatten(value) : undefined);
if (!isEmpty(value)) {
const flattened: any = flatten(value, { safe: true });
const convertedValues = Object.entries(flattened).map(([key, value]) =>
Array.isArray(value) ? [key, value[0]] : [key, value]
);
setValue(key, unflatten(Object.fromEntries(convertedValues)));
} else {
setValue(key, undefined);
}
} else {
setValue(key, value);
}