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)

1
  • 1
    You've hardcoded the property name key, see computed property names. Commented Jun 4, 2020 at 9:45

2 Answers 2

4

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Did not know about the square bracket method to use a string as the name of the key, thanks for that!
Note: it is not working on ES5
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.