Skip to content

Instantly share code, notes, and snippets.

@yazinsai
Last active November 1, 2021 19:00
Show Gist options
  • Save yazinsai/d63c42deb4ca42dff137bc652f5c9360 to your computer and use it in GitHub Desktop.
Save yazinsai/d63c42deb4ca42dff137bc652f5c9360 to your computer and use it in GitHub Desktop.
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