diff --git a/src/decorator/array/ArrayUnique.ts b/src/decorator/array/ArrayUnique.ts index 0979aeefc0..98d00efeaa 100644 --- a/src/decorator/array/ArrayUnique.ts +++ b/src/decorator/array/ArrayUnique.ts @@ -12,7 +12,7 @@ export function arrayUnique(array: unknown[], identifier?: ArrayUniqueIdentifier if (!Array.isArray(array)) return false; if (identifier) { - array = array.map(o => (o != null ? identifier(o) : o)); + array = array.flatMap(o => (o != null ? identifier(o) : o)); } const uniqueItems = array.filter((a, b, c) => c.indexOf(a) === b); diff --git a/test/functional/validation-functions-and-decorators.spec.ts b/test/functional/validation-functions-and-decorators.spec.ts index 5144a0db48..b781d4b137 100644 --- a/test/functional/validation-functions-and-decorators.spec.ts +++ b/test/functional/validation-functions-and-decorators.spec.ts @@ -4610,6 +4610,51 @@ describe('ArrayUnique with identifier', () => { }); }); +describe('ArrayUnique with array return values', () => { + const identifier = o => o.name; + const validValues = [ + [['world'], ['hello'], ['superman']], + [['world', 'superman'], ['hello']], + [['superman', 'world', 'hello']], + [['1'], ['2'], [null], [undefined]], + ].map(list => list.map(name => ({ name }))); + const invalidValues: any[] = [ + null, + undefined, + [['world'], ['hello'], ['hello']], + [['world'], ['hello', 'hello']], + [['world', 'hello'], ['world']], + [['1'], ['1'], ['1']], + ].map(list => list?.map(name => (name != null ? { name } : name))); + + class MyClass { + @ArrayUnique(identifier) + someProperty: { name: string }[]; + } + + it('should not fail if validator.validate said that its valid', () => { + return checkValidValues(new MyClass(), validValues); + }); + + it('should fail if validator.validate said that its invalid', () => { + return checkInvalidValues(new MyClass(), invalidValues); + }); + + it('should not fail if method in validator said that its valid', () => { + validValues.forEach(value => expect(arrayUnique(value, identifier)).toBeTruthy()); + }); + + it('should fail if method in validator said that its invalid', () => { + invalidValues.forEach(value => expect(arrayUnique(value, identifier)).toBeFalsy()); + }); + + it('should return error object with proper data', () => { + const validationType = 'arrayUnique'; + const message = "All someProperty's elements must be unique"; + return checkReturnedError(new MyClass(), invalidValues, validationType, message); + }); +}); + describe('isInstance', () => { class MySubClass { // Empty