2

I have for some time wondered if there is any quicker way to instantiate a chain of objects in in javascript.

Lets say that we for instance have the following "chain of objects"

window.myobject1.myobject2.myobject3 = {}

This will ofcourse not work.. since object1 and object2 are not instantiated.. however.. to get this to work.. I would have to do something like:

window.myobject1 = {}
window.myobject1.myobject2 = {}
window.myobject1.myobject2.myobject3 = {}

Which simply just seems silly.. in a more realistic case.. lets say we have

window.server.responses.currentuser.id

where server,responses and currentuser simply act as "namespaces"/empty enities.. Would there be any way where I can tell javascript to instantiate the whole chain as objects?.. so I don't need to instantiate each part of the chain on a new line?

This might be a bad example but I guess you get it.. for instance I might also have:

window.server.responses.currentuser.id
window.server.responses.theotherusers.personone.id
window.server.responses.labels.personname

etc..

Thanks in advance!

wprl
  • 24,489
  • 11
  • 55
  • 70
Inx
  • 2,364
  • 7
  • 38
  • 55

1 Answers1

-1

I've answered this question before but can't seem to find it so can't mark this as duplicate (hehe). Anyway, you can basically do it with a function:

function deep_set (obj,path,value) {
    var name = path.shift();
    if (path.length) {
        if (typeof obj[name] == undefined) {
            obj[name] = {};
        }
        if (typeof obj[name] == 'string' || typeof obj[name] == 'number') {
            throw new Error('attempted to access string or number as object');
        }
        deep_set(obj[name],path,value);
    }
    else {
        obj[name] = value;    
    }
}

So you can now do:

deep_set(window,['server','responses','currentuser','id'],3);

without having to manually test typeof == undefined at each step.

With a little change you can have the API look any way you want:

window.deep_set(['server','responses','currentuser','id'],3);
// or
deep_set(window,'server','responses','currentuser','id',3);
// or
deep_set(window,'server.responses.currentuser.id',3);
slebetman
  • 109,858
  • 19
  • 140
  • 171