2

For example, I wish to create an object at the end of a nested chain of objects, eg:

window.a.b.c.d = {}

But I need to check if the parameters a, b, and c exist, else create them. As far as I know, you need to do this:

window.a = window.a || {};
window.a.b = window.a.b || {};
window.a.b.c = window.a.b.c || {};
window.a.b.c.d = {};

Is there a faster/better ("one liner") method?

ZephDavies
  • 3,964
  • 2
  • 14
  • 19
  • There is better if you write a method. If you want a quick and dirty one-liner, you can do a try… catch and see if you have a ReferenceError. – Touffy Jun 22 '16 at 14:58
  • 1
    You can see how many keys the object currently has with `Object.keys(obj).length` – Jeremy Jackson Jun 22 '16 at 15:01
  • You can skip writing `window.` from the 2nd statement onwards: `window.a = window.a || {}; a.b = a.b || {}; a.b.c = a.b.c || {}; a.b.c.d = {};`. – Dogbert Jun 22 '16 at 15:07
  • http://stackoverflow.com/a/383245/2464634 MergeRecursive(window, {a: {b : {c : {d : {}}}}}); – Preston S Jun 22 '16 at 15:49

2 Answers2

2

You can just write the object as below:

window.a = {
    b: {
        c: {
            d: {
            }
        }
    }
};

But when you want to make this on existent objects, it's better to write a function.

Example:

/**
 * Create object(s) in a object.
 * 
 * @param object obj
 * @param array  path
 */
function createObjectPath(obj, path) {

    var currentPath = obj;

    // Iterate objects in path
    for(var i = 0, p; p = path[i]; i++) {

        // Check if doesn't exist the object in current path
        if(typeof currentPath[p] !== 'object') {

            currentPath[p] = {};
        }

        currentPath = currentPath[p];
    }
}

And you could use this function so:

createObjectPath(window, ['a', 'b', 'c', 'd']);

The function creates a reference of a argumented object in 1st parameter, then iterate over each string in the array argumented in the 2nd parameter and set each string as a object case doesn't exist in a parent object.

0

Lodash's set does exactly this in a one-liner (ignoring import)

import { set } from 'lodash'

set(window, 'a.b.c.d', {})
ZephDavies
  • 3,964
  • 2
  • 14
  • 19