1

I would like to use an integer as a JSON object key :

let myJKey = 1  

let myJSONArrayObject = { filter: [] }  

myJSONObject.filter.push({myJKey: 'a json value'})  

However, I get : `{"filter":[{"myJKey":{"a json value"}}]}`   

How should I set up so the I get the value 1 in the myKey variable as the JSON key?

Program-Me-Rev
  • 6,184
  • 18
  • 58
  • 142

3 Answers3

2

Using [] (Bracket notation)

let myJKey = 1  

let myJSONArrayObject = { filter: [] }  

myJSONArrayObject.filter.push({[myJKey]: 'a json value'})  

console.log(myJSONArrayObject)
User863
  • 19,346
  • 2
  • 17
  • 41
1

You are missing []

myJSONArrayObject.filter.push({[myJKey]: 'a json value'})  
Kannan G
  • 974
  • 6
  • 9
1
myJSONObject.filter.push({myJKey: 'a json value'})

Should be:-

myJSONObject.filter.push({[myJKey]: 'a json value'})

This is a ES6 syntax. Supporting in many browsers