Javascript: how to dynamically create nested objects using object names given by an array Javascript: how to dynamically create nested objects using object names given by an array arrays arrays

Javascript: how to dynamically create nested objects using object names given by an array


Put in a function, short and fast (no recursion).

var createNestedObject = function( base, names ) {    for( var i = 0; i < names.length; i++ ) {        base = base[ names[i] ] = base[ names[i] ] || {};    }};// Usage:createNestedObject( window, ["shapes", "triangle", "points"] );// Now window.shapes.triangle.points is an empty object, ready to be used.

It skips already existing parts of the hierarchy. Useful if you are not sure whether the hierarchy was already created.

Or:

A fancier version where you can directly assign the value to the last object in the hierarchy, and you can chain function calls because it returns the last object.

// Function: createNestedObject( base, names[, value] )//   base: the object on which to create the hierarchy//   names: an array of strings contaning the names of the objects//   value (optional): if given, will be the last object in the hierarchy// Returns: the last object in the hierarchyvar createNestedObject = function( base, names, value ) {    // If a value is given, remove the last name and keep it for later:    var lastName = arguments.length === 3 ? names.pop() : false;    // Walk the hierarchy, creating new objects where needed.    // If the lastName was removed, then the last object is not set yet:    for( var i = 0; i < names.length; i++ ) {        base = base[ names[i] ] = base[ names[i] ] || {};    }    // If a value was given, set it to the last name:    if( lastName ) base = base[ lastName ] = value;    // Return the last object in the hierarchy:    return base;};// Usages:createNestedObject( window, ["shapes", "circle"] );// Now window.shapes.circle is an empty object, ready to be used.var obj = {}; // Works with any object other that window toocreateNestedObject( obj, ["shapes", "rectangle", "width"], 300 );// Now we have: obj.shapes.rectangle.width === 300createNestedObject( obj, "shapes.rectangle.height".split('.'), 400 );// Now we have: obj.shapes.rectangle.height === 400

Note: if your hierarchy needs to be built from values other that standard objects (ie. not {}), see also TimDog's answer below.

Edit: uses regular loops instead of for...in loops. It's safer in cases where a library modifies the Array prototype.


function assign(obj, keyPath, value) {   lastKeyIndex = keyPath.length-1;   for (var i = 0; i < lastKeyIndex; ++ i) {     key = keyPath[i];     if (!(key in obj)){       obj[key] = {}     }     obj = obj[key];   }   obj[keyPath[lastKeyIndex]] = value;}

Usage:

var settings = {};assign(settings, ['Modules', 'Video', 'Plugin'], 'JWPlayer');


My ES2015 solution. Keeps existing values.

const set = (obj, path, val) => {     const keys = path.split('.');    const lastKey = keys.pop();    const lastObj = keys.reduce((obj, key) =>         obj[key] = obj[key] || {},         obj);     lastObj[lastKey] = val;};

Example:

const obj = {'a': {'prop': {'that': 'exists'}}};set(obj, 'a.very.deep.prop', 'value');console.log(JSON.stringify(obj));// {"a":{"prop":{"that":"exists"},"very":{"deep":{"prop":"value"}}}}