2

I am trying to do the followings:

var Colors = {
    'BLUE    ': 1,
    'RED'    : 2,
    'YELLOW' : 3
};

var Boxes = {
    Colors.BLUE   : 5,
    Colors.RED    : 1,
    Colors.YELLOW : 0
};

console.log(Boxes);

However, I get the following error:

Uncaught SyntaxError: Unexpected token .

How do I go about referencing the Colors object while defining Boxes?

I would like to do this using only the object literal syntax. Thanks.

RainSear
  • 629
  • 1
  • 8
  • 13

2 Answers2

2

You will have to be more verbose and use bracket notation to define variable property names:

var Colors = {
    'BLUE'   : 1,
    'RED'    : 2,
    'YELLOW' : 3
};

var Boxes = {};
Boxes[Colors.BLUE] = 5;
Boxes[Colors.RED] = 1;
Boxes[Colors.YELLOW] = 0;

console.log(Boxes);

In ES2015 however you can use expressions to initialize object keys, this is known as Computed property names:

var Boxes = {
    [Colors.BLUE]   : 5,
    [Colors.RED]    : 1,
    [Colors.YELLOW] : 0
};
dfsq
  • 191,768
  • 25
  • 236
  • 258
0

You can define an Object as a property of another Object such as:

var Colors = {
    BLUE: 1,
    RED: 2,
    YELLOW : 3
};

var Boxes = {
    Colors: Colors
}

console.log(Boxes);

Or you can simply define the whole object as one such as:

var Boxes = {
    Colors: {
        BLUE: 1,
        RED: 2,
        YELLOW : 3
    }
}

console.log(Boxes);

Should get the results you need.

ivanspaeth
  • 46
  • 2