0

What I'm trying to achieve is the following structure for an object. Note that all properties values are constant strings:

ObjA
    ObjB
        prop1
        prop2
        prop3
    ObjC
        prop4
        prop5
    .
    .
    .

So shoud it be possible to access the properties value using the following sintax:

alert(ObjA.ObjC.pro4);

So far, I've tried something like the following without success.

    var csi = new Object();
    var cao98 = new Object();
    csi.cao98="";
    csi.cao98.rgi = "NRRGILIG";
    alert (csi.cao98.rgi);

Is it possible? I do not want to get to far on this issue since there's a lot of discussion on this theme.

Matt
  • 74,352
  • 26
  • 153
  • 180
Paulo Bueno
  • 2,499
  • 6
  • 42
  • 68

3 Answers3

2

On your third line you’re assigning an empty string to the cao98 property of your csi object.

I think you mean this instead:

var csi = new Object();
var cao98 = new Object();
csi.cao98=cao98;
csi.cao98.rgi = "NRRGILIG";
alert (csi.cao98.rgi);

If you’re just literally defining your objects like this, you could use the object literal syntax instead:

var csi = {
    cao98: {
        rgi: "NRRGILIG"
    }
};

alert (csi.cao98.rgi);

The best approach depends on the context in which you’re using the objects.

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
  • So is it ok to construct this way? I mean, there should be dozens of 'nested' objects. – Paulo Bueno Dec 05 '12 at 14:04
  • Is it ok to construct *which* way? I don’t think there’s much difference between the two, although there is a Stack Overflow question on the subject: http://stackoverflow.com/questions/4597926/creating-objects-new-object-or-object-literal-notation – Paul D. Waite Dec 05 '12 at 14:14
  • The object literal syntax is arguably more readable, when indented. (JSON is sort of a subset of JavaScript’s object literal syntax, so it’s got a reasonable chance of looking familiar even to non-JavaScript programmers too.) – Paul D. Waite Dec 05 '12 at 14:24
2

If you just want plain objects, you can write that all into one expression using the literal syntax for objects:

var ObjA = {
        ObjB: {
            prop1: 'hello',
            prop2: 'howdy'
        },
        ObjC: {
            prop1: 'hi',
            prop2: 'world'
        }
    }
}

console.log(ObjA.ObjB.prop1 + ' ' + ObjA.ObjC.prop2);
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0

try

    var csi = {
        cao: {
            rgi: 'NRRGILIG'
        }
    };
nozzleman
  • 9,529
  • 4
  • 37
  • 58