Last active
November 1, 2021 19:00
-
-
Save yazinsai/d63c42deb4ca42dff137bc652f5c9360 to your computer and use it in GitHub Desktop.
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
export const flattenObjectToMongoDbFormat = (obj: any, parent: String = ''): any => { | |
/** | |
* When you want to update a MongoDB document, without overriding | |
* nested fields that are not specified, you need to specify the | |
* nested fields in the format: | |
* `$set: { "parent.nested.key": "value" }` | |
* | |
* This method takes a nested object (usually from an incoming API | |
* request) and converts it to the nested format. | |
*/ | |
const flattened:any = {} | |
for (const key of Object.keys(obj)) { | |
const value = obj[key] | |
const flatKey = parent.length ? `${parent}.${key}` : key | |
if (typeof value === 'object') { | |
const result = flattenObjectToMongoDbFormat(value, flatKey) | |
for (const subKey of Object.keys(result)) { | |
flattened[`${flatKey}.${subKey}`] = result[subKey] | |
} | |
} else { | |
flattened[`${key}`] = value | |
} | |
} | |
return flattened | |
} | |
// Example usage below: | |
flattenObjectToMongoDbFormat({ | |
age: 12, | |
job: { | |
company: "Acme Corp", | |
title: "CEO" | |
} | |
}) | |
// => | |
// { 'age': 12, 'job.company': 'Acme Corp', 'job.title': 'CEO' } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment