Created
March 4, 2017 11:11
-
-
Save BoLaMN/b9ba4a924c4488a8283c6b63b43e712b 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
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