Created
November 1, 2021 19:49
-
-
Save yazinsai/28b3098edd2034b906ed592ce7c26c29 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
const flattenObjectToMongoDbFormat = (obj, ancestors = []) => { | |
/** | |
* 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 flat = {}; | |
for (const key of Object.keys(obj)) { | |
const value = obj[key]; | |
if (typeof value === 'object') { | |
// Recurse, combine and bubble results upwards | |
Object.assign(flat, flattenObjectToMongoDbFormat(value, [...ancestors, key])); | |
} | |
else { | |
// Base case | |
const deepKey = [...ancestors, key].join('.'); | |
flat[deepKey] = value; | |
} | |
} | |
return flat; | |
}; | |
// Example run | |
flattenObjectToMongoDbFormat({ | |
age: 12, | |
job: { | |
company: "Acme Corp", | |
title: "CEO" | |
} | |
}) | |
// Output: | |
// { 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