Created
September 24, 2023 16:55
-
-
Save marcj/b4634134872efd8f258447f6ac163797 to your computer and use it in GitHub Desktop.
Deepkit dot path to objects serializer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
test('dot path to objects', () => { | |
//given values like { "myArray[0].prop1.prop2": "123" } we want to convert it to { myArray: [{ prop1: { prop2: "123" } }] } | |
interface MyObject { | |
myArray: { prop1: { prop2: string } }[]; | |
} | |
function convertPathObjectToValues(object: { [name: string]: any }): any { | |
//object has keys like "myArray[0].prop1.prop2" | |
//and we want to convert it to { myArray: [{ prop1: { prop2: "123" } }] } | |
const result: any = {}; | |
for (const [path, value] of Object.entries(object)) { | |
const parts = path.split('.'); | |
let current = result; | |
for (let i = 0; i < parts.length; i++) { | |
const part = parts[i]; | |
const isArray = part.includes('['); | |
const name = isArray ? part.substr(0, part.indexOf('[')) : part; | |
const index = isArray ? parseInt(part.substr(part.indexOf('[') + 1, part.indexOf(']') - part.indexOf('[') - 1)) : undefined; | |
if (i === parts.length - 1) { | |
current[name] = value; | |
} else { | |
if (isArray && index !== undefined) { | |
if (!current[name]) current[name] = []; | |
if (!current[name][index]) current[name][index] = {}; | |
current = current[name][index]; | |
} else { | |
if (!current[name]) current[name] = {}; | |
current = current[name]; | |
} | |
} | |
} | |
} | |
return result; | |
} | |
const mySerializer = new class extends Serializer { | |
override registerSerializers() { | |
super.registerSerializers(); | |
this.deserializeRegistry.prepend(ReflectionKind.objectLiteral, (type, state) => { | |
//convert dot path to object | |
state.setContext({ convertPathObjectToValues }); | |
state.addCodeForSetter(`${state.setter} = convertPathObjectToValues(${state.accessor});`); | |
}); | |
} | |
}; | |
const myObjectRaw: any = { 'myArray[0].prop1.prop2': '123' }; | |
const myObject = deserialize<MyObject>(myObjectRaw, undefined, mySerializer); | |
console.log(myObject.myArray[0].prop1.prop2); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment