Skip to content

Instantly share code, notes, and snippets.

@BoLaMN
Created March 4, 2017 11:11
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/b9ba4a924c4488a8283c6b63b43e712b to your computer and use it in GitHub Desktop.
Save BoLaMN/b9ba4a924c4488a8283c6b63b43e712b to your computer and use it in GitHub Desktop.
let primitiveTypes = [
'number',
'boolean',
'string'
];
var flatten = function(parent, prefix, child) {
if (isPrimitive(child)) {
if (!parent) {
parent = {};
}
if (child != null) {
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]));
}
};
var isPrimitive = value => (primitiveTypes.indexOf(typeof value) !== -1) || util.isDate(value) || (value === null) || (value === undefined) || (value.constructor && (value.constructor.name === 'ObjectID'));
let convertToDotNotation = function(value) {
if (!value || isPrimitive(value)) {
return value;
}
let obj = {};
flatten(obj, null, value);
return obj;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment