Skip to content

Instantly share code, notes, and snippets.

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