Last active
February 24, 2017 23:41
-
-
Save kevinweber/3379d63a67d8e6296bb31e768851c3dc to your computer and use it in GitHub Desktop.
Convert dot-notated string or path of object into an object using recursion. This is similar to Lodash's _.zipObject but it doesn't set any values.
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
/** | |
* Convert an array into an object where each object gets nested like this: | |
['string1', 'string2', 'string3'] | |
becomes | |
{ | |
string1: { | |
string2: { | |
string3: {} | |
} | |
} | |
} | |
* @param {array} array | |
* @param {object} [object] Will be merged with the new nested objects. Overlapping/existing properties will be overridden. | |
* | |
* @returns {object} | |
*/ | |
const arrayToNestedObject = function arrayToNestedObjectR(array, object) { | |
object = object || {}; | |
if (array.length > 0) { | |
const firstInArray = array[0]; | |
array.shift(); | |
object[firstInArray] = {}; | |
if (array.length > 0) { | |
object[firstInArray] = arrayToNestedObjectR(array, object[firstInArray]); | |
} | |
} | |
return object; | |
}; | |
/** | |
* Convert a dot-notated string such as 'string1.string2.string3' into an object. | |
* See "arrayToNestedObject". | |
* | |
* @param {array} string Expects a bunch of strings separated by ".". | |
* @param {object} [object] Will be merged with the new nested objects. Overlapping/existing properties will be overridden. | |
* | |
* @returns {object} | |
*/ | |
export function dotNotationToNestedObject(string, object) { | |
if (string.indexOf('.') > -1) { | |
return arrayToNestedObject(string.split('.'), object); | |
} else { | |
let justOneLevel = {}; | |
justOneLevel[string] = {}; | |
return justOneLevel; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment