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:
parent
afbc047c77
commit
422af36d2d
35
src/lib/util/flattenPayload.test.ts
Normal file
35
src/lib/util/flattenPayload.test.ts
Normal 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,
|
||||
});
|
||||
});
|
||||
});
|
32
src/lib/util/flattenPayload.ts
Normal file
32
src/lib/util/flattenPayload.ts
Normal 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;
|
||||
}, {});
|
Loading…
Reference in New Issue
Block a user