-2

Consider this:

var items = {};
var id = 'varID';
if (typeof items.id == 'undefined') {
    items.id = {};
}

From what I understand, this assigns the empty property id to the plain object items.

How can I assign the property varID to the plain object items instead, using the variable id?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

1 Answers1

5

Try

items[id] = items[id] || {}; //Does the same work as the if statement

instead of items.id. With this you can assign dynamic properties. (Trust me, I had the same problem once.)

Or you can use Object.defineProperty(obj, prop, descriptor) (a little bit different).

Quoting the documentation:

The Object.defineProperty() method defines a new property directly on an object 
or modifies an existing property on an object, and returns the object.

Check out more in Object.defineProperty().

These are two ways of doing the trick. Clearly the second one is a little bit different from the first one that is simpler.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
steo
  • 4,586
  • 2
  • 33
  • 64