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

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

No, that does not work like that.

The variable name is a reference to an object in a heap area of memory managed by JS automatically for you.

In details it means that:

var boxA = {color: "red", width: 100};

this statement:

  1. Creates an object in the heap
  2. Associates a local symbol boxA with that object.

So the object is referenced by one variable yet.

var boxArray = [boxA];

here:

  1. An array with one element is created. That element contains a reference to an object. A copy of the reference to be precise. So, the same original object is referenced twice now.
  2. A boxArray is assigned a reference to the array, which is also placed in the heap.

To summarize: the variable names exist only in code listing for developers to easier reason about some objects in memory, instead of operating with memory addresses (which would be horrible).


Well the boxArray is filled with values of variables you are putting in it. Example: If you would save three integer variables not the names of variables. So your new boxArray is equal to:

boxArray = [{color: "red", width: 100},{color: "yellow", width: 200},{color: "blue", width: 300}];

If you're looking to get the keys of an object try Object.keys(object)

Object.keys(boxA)
["color", "width"]