Skip to content

Instantly share code, notes, and snippets.

@kevinweber
Last active February 24, 2017 23:41
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 kevinweber/3379d63a67d8e6296bb31e768851c3dc to your computer and use it in GitHub Desktop.
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.
/**
* 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