1

I'm trying to use a unique ID to store a JSON object in an array so that I can pull out that specific object at a later date in my code, however my expected output isn't happening:

var applications = []

var key = 50

var obj = {
  key: {
    "name": "John"
  }
}

// expected output:
//
// [{
//   '50': {
//     "name": "John"
//   }
// }]
// 

applications.push(obj)

Ryan H
  • 2,620
  • 4
  • 37
  • 109
  • 1
    You've hardcoded the property name `key`, see [computed property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Examples). – Teemu Jun 04 '20 at 09:45

2 Answers2

3

In order to use a dynamic key, we just need to wrap that key in square brackets [] like:

var applications = []
var key = 50
var obj = {
  [key]: {
    "name": "John"
  }
}
applications.push(obj)

console.log(applications)
palaѕн
  • 72,112
  • 17
  • 116
  • 136
0

Adding [] is available from ES6 and Babel and not ES5

For compatibility you need to make the object first, then use [] to set it.

var key = 50;
var obj = {};
obj[key] = someValueArray;
applications.push(obj);
Hamza Ezzaydia
  • 267
  • 2
  • 13