Skip to content

Instantly share code, notes, and snippets.

@BoLaMN
Last active March 6, 2017 07:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BoLaMN/b69979b6dca800fd23579c32900593ba to your computer and use it in GitHub Desktop.
Save BoLaMN/b69979b6dca800fd23579c32900593ba to your computer and use it in GitHub Desktop.
let isPrimitive = function(value) {
let primitiveTypes = [
'number',
'boolean',
'string'
];
return (primitiveTypes.indexOf(typeof value) !== -1) || util.isDate(value) || (value === null) || (value.constructor && (value.constructor.name === 'ObjectID'));
};
let convertToDotNotation = function(value, modelClass) {
if (!value || isPrimitive(value)) {
return value;
}
let obj = {};
var flatten = function(parent, prefix, child) {
if (!child) {
return;
}
if (isPrimitive(child)) {
if (!parent) {
parent = {};
}
parent[prefix] = child;
return;
}
let getPrefix = function(key) {
if (!prefix) { return key; } else { return prefix + '.' + key; }
};
if (Array.isArray(child)) {
child.forEach((c, index) => flatten(parent, getPrefix(index), c));
} else {
Object.keys(child).forEach(key => flatten(parent, getPrefix(key), child[key]));
}
};
let { relations } = modelClass.model;
Object.keys(relations).forEach(function(relationName) {
let { embed, keyFrom } = relations[relationName];
if (embed) {
flatten(value, keyFrom, value[keyFrom]);
return delete value[keyFrom];
}});
return value;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment