1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-01-20 00:08:02 +01:00

chore: flatten payload util (#6531)

https://linear.app/unleash/issue/2-2029/support-filtering-on-nested-properties

This will allow us to support and suggest payload subproperties in the
action filters.
This commit is contained in:
Nuno Góis 2024-03-13 11:10:44 +00:00 committed by GitHub
parent afbc047c77
commit 422af36d2d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 67 additions and 0 deletions

View File

@ -0,0 +1,35 @@
import { flattenPayload } from './flattenPayload';
describe('flattenPayload', () => {
it('should flatten a payload', () => {
const payload = {
a: 1,
b: {
c: 2,
d: [3, 4],
e: {
f: 5,
},
},
};
expect(flattenPayload(payload)).toEqual({
a: 1,
'b.c': 2,
'b.d[0]': 3,
'b.d[1]': 4,
'b.e.f': 5,
});
});
it('should handle conflicting keys gracefully by prioritizing later keys', () => {
const payload = {
a: {
b: 1,
},
'a.b': 2,
};
expect(flattenPayload(payload)).toEqual({
'a.b': 2,
});
});
});

View File

@ -0,0 +1,32 @@
export const flattenPayload = (
payload = {},
parentKey = '',
): Record<string, unknown> =>
Object.entries(payload).reduce((acc, [key, value]) => {
const newKey = parentKey ? `${parentKey}.${key}` : key;
if (
typeof value === 'object' &&
value !== null &&
!Array.isArray(value)
) {
// If it's an object, recurse and merge the results
Object.assign(acc, flattenPayload(value, newKey));
} else if (Array.isArray(value)) {
// If it's an array, map through it and handle objects and non-objects differently
value.forEach((item, index) => {
if (typeof item === 'object' && item !== null) {
Object.assign(
acc,
flattenPayload(item, `${newKey}[${index}]`),
);
} else {
acc[`${newKey}[${index}]`] = item;
}
});
} else {
acc[newKey] = value;
}
return acc;
}, {});