Skip to content

Commit

Permalink
Merge pull request #4853 from armellarcier/fix-sanitizeEmptyValues-4726
Browse files Browse the repository at this point in the history
[RFR] Support array of objects in sanitizeEmptyValues
  • Loading branch information
fzaninotto authored May 26, 2020
2 parents c4f0fb3 + b603381 commit 5e247b9
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
19 changes: 19 additions & 0 deletions packages/ra-core/src/form/sanitizeEmptyValues.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,25 @@ describe('sanitizeEmptyValues', () => {
sanitizeEmptyValues({ obj: { foo: null, foo2: 2 } }, { obj })
).toEqual({ obj: { foo: { bar: 1 }, foo2: null } });
});
it('should accept object values in arrays', () => {
const obj = [{ foo: 1 }, { foo: 2 }];
expect(sanitizeEmptyValues({ obj }, { obj: [{ foo: 1 }, {}] })).toEqual(
{ obj: [{ foo: 1 }, { foo: null }] }
);
expect(sanitizeEmptyValues({}, { obj })).toEqual({ obj });
});
it('should accept adding objects in arrays', () => {
const obj = [{ foo: 1, foo2: 2 }, { foo: 3 }, { foo: 4 }];
expect(
sanitizeEmptyValues({ obj: [{ foo: 1 }, { foo: 4 }] }, { obj })
).toEqual({ obj: [{ foo: 1, foo2: 2 }, { foo: 3 }, { foo: 4 }] });
});
it('should accept removing objects in array of objects', () => {
const obj = [{ foo: 1, foo2: 2 }, { foo: 3 }, { foo: 4 }];
expect(
sanitizeEmptyValues({ obj }, { obj: [{ foo: 1 }, { foo: 4 }] })
).toEqual({ obj: [{ foo: 1, foo2: null }, { foo: 4 }] });
});
it("should not ignore initial value when it's not of the same type", () => {
const initialValues = { a: 'foobar' };
const values = { a: { hello: 'world' } };
Expand Down
10 changes: 9 additions & 1 deletion packages/ra-core/src/form/sanitizeEmptyValues.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,16 @@ const sanitizeEmptyValues = (initialValues: object, values: object) => {
if (!initialValues) return values;
const initialValuesWithEmptyFields = Object.keys(initialValues).reduce(
(acc, key) => {
if (values[key] instanceof Date || Array.isArray(values[key])) {
if (values[key] instanceof Date) {
acc[key] = values[key];
} else if (Array.isArray(values[key])) {
if (Array.isArray(initialValues[key])) {
acc[key] = values[key].map((value, index) =>
sanitizeEmptyValues(initialValues[key][index], value)
);
} else {
acc[key] = values[key];
}
} else if (
typeof values[key] === 'object' &&
typeof initialValues[key] === 'object' &&
Expand Down

0 comments on commit 5e247b9

Please sign in to comment.