mirror of
https://github.com/directus/directus.git
synced 2026-04-25 03:00:53 -04:00
Move get-with-arrays to shared (#15332)
* Move get-with-arrays to shared, add fallback * Just fallback to undefineds, let the usage handle fallbacks
This commit is contained in:
18
packages/shared/src/utils/get-with-arrays.test.ts
Normal file
18
packages/shared/src/utils/get-with-arrays.test.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { test, expect } from 'vitest';
|
||||
|
||||
import { get } from './get-with-arrays';
|
||||
|
||||
test('Returns static value from object', () => {
|
||||
const input = { test: { path: 'example' } };
|
||||
expect(get(input, 'test.path')).toBe('example');
|
||||
});
|
||||
|
||||
test('Returns default value if path does not exist in object', () => {
|
||||
const input = { test: { path: 'example' } };
|
||||
expect(get(input, 'test.wrong', 'default value')).toBe('default value');
|
||||
});
|
||||
|
||||
test('Returns values in array path as flattened array', () => {
|
||||
const input = { test: [{ path: 'example' }, { path: 'another' }] };
|
||||
expect(get(input, 'test.path')).toEqual(['example', 'another']);
|
||||
});
|
||||
21
packages/shared/src/utils/get-with-arrays.ts
Normal file
21
packages/shared/src/utils/get-with-arrays.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Basically the same as `get` from `lodash`, but will convert nested array values to arrays, so for example:
|
||||
*
|
||||
* @example
|
||||
* ```js
|
||||
* const obj = { value: [{ example: 1 }, { example: 2 }]}
|
||||
* get(obj, 'value.example');
|
||||
* // => [1, 2]
|
||||
* ```
|
||||
*/
|
||||
export function get(object: Record<string, any> | any[], path: string, defaultValue?: unknown): any {
|
||||
const [key, ...follow] = path.split('.');
|
||||
|
||||
const result = Array.isArray(object) ? object.map((entry) => entry?.[key!]) : object?.[key!];
|
||||
|
||||
if (follow.length > 0) {
|
||||
return get(result, follow.join('.'), defaultValue);
|
||||
}
|
||||
|
||||
return result ?? defaultValue;
|
||||
}
|
||||
@@ -15,6 +15,7 @@ export * from './get-functions-for-type';
|
||||
export * from './get-output-type-for-function';
|
||||
export * from './get-relation-type';
|
||||
export * from './get-simple-hash';
|
||||
export * from './get-with-arrays';
|
||||
export * from './is-dynamic-variable';
|
||||
export * from './merge-filters';
|
||||
export * from './move-in-array';
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { get, isObjectLike } from 'lodash';
|
||||
import { isObjectLike } from 'lodash';
|
||||
import { REGEX_BETWEEN_PARENS } from '../constants';
|
||||
import { Accountability, Filter, Role, User } from '../types';
|
||||
import { adjustDate } from './adjust-date';
|
||||
import { deepMap } from './deep-map';
|
||||
import { get } from './get-with-arrays';
|
||||
import { isDynamicVariable } from './is-dynamic-variable';
|
||||
import { toArray } from './to-array';
|
||||
|
||||
|
||||
Reference in New Issue
Block a user