Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In an array of named objects in javascript - are the names accessible?

If we create some objects, and fill an array with those objects, are the names stored within the array, or only the properties of the object? I guess this may be trivial, but I haven't been able to find an answer.

var boxA = {color: "red", width: 100};
var boxB = {color: "yellow", width: 200};
var boxC = {color: "blue", width: 300};

boxArray = [boxA, boxB, boxC];

for (var i = 0; i < boxArray.length; i++) {

    //****
    // What code do we insert here to log
    // boxA
    // boxB
    // boxC
    //****

}

Of course, it is a trivial workaround to add

boxA.box = boxA; 

etc and then call

console.log(boxArray[i].box);

But is that really necessary?

like image 714
SauceCode Avatar asked Dec 19 '22 03:12

SauceCode


1 Answers

To answer your question directly - no, you can't do what you're asking. I've run into the same scenario a few times. Here's what I've done. Instead of using an array, you could just add your objects to an object literal instead, and map the object to some unique key, such as an id.

var boxes = {
  boxA: { color: 'red', width: 100 },
  boxB: { color: 'blue', width: 200 },
  boxC: { color: 'yellow', width: 300 },
};

for (var boxKey in boxes) {
  console.log(boxKey);
}

// to use
boxes.boxA; // do something with boxA
like image 98
Danny Bullis Avatar answered Dec 24 '22 03:12

Danny Bullis