0

I am coming across the following error in js

Cannot read property 'charlie' of undefined 

I am setting a value like this

alpha.beta.charlie.delta.echo = [];

but only alpha and beta are initialized as objects. So how do I auto initialize objects charlie and echo as objects without writing

alpha.beta.charlie = {};
alpha.beta.charlie.delta = {}
alpha.beta.charlie.delta.echo = [];
Tim Joyce
  • 4,487
  • 5
  • 34
  • 50
  • Duplicate? http://stackoverflow.com/questions/5484673/javascript-how-to-dynamically-create-nested-objects-using-object-names-given-by – Holf Sep 04 '13 at 16:34
  • `beta` does not seem to initialized already when the error message states that you're accessing `charlie` on `undefined` – Bergi Sep 04 '13 at 16:40
  • Agree with @Bergi The error Cannot read property 'charlie' of undefined indicates that beta is not defined, so only alpha is defined at this point – Robert Sep 04 '13 at 16:55

4 Answers4

1

Have to init all..

alpha={beta:{charlie:{delta:[]}};

then alpha.beta.charlie.delta would be your [] Empty array;

Robert
  • 386
  • 1
  • 8
  • Please don't use `==` like that in code (your expression would yield false). Make it a comment at least, or use a symbol like ≙ – Bergi Sep 04 '13 at 16:58
1

You don't - about the best you can do is something like this:

alpha.beta = { charlie: { delta: { echo: [] } } };

Of you don't know whether the objects are initialized yet or not, it would be safer to keep the first form and do something like this:

alpha.beta                    = alpha.beta || {};
alpha.beta.charlie            = alpha.beta.charlie || {};
alpha.beta.charlie.delta      = alpha.beta.charlie.delta || {}
alpha.beta.charlie.delta.echo = alpha.beta.charlie.delta.echo  || [];
dc5
  • 12,341
  • 2
  • 35
  • 47
0

At some point you have to declare alpha properties, one shorter version of doing so is

alpha.beta.charlie = {
  delta: {
    echo: []
  }
}
Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
0

There is no auto-initialisation possible in javascript (unless from ugly hacks with proxies or with knowing the property names in before).

Instead, just nest the object literals to create the properties directly on them, instead of creating empty objects and putting properties on them afterwards:

alpha.beta = {
    charlie = {
        delta: {
            echo: []
        }
    }
};

or short

alpha.beta = {charlie: {delta: {echo: []}}};
Bergi
  • 630,263
  • 148
  • 957
  • 1,375