dynamically assign key in json using javasctipt

I am trying to find a way to dynamically assign keynames when creating my json object using java script.
This issue I have is that the stringfy option ignores the value for the key name but it does interpet the key value
..
..

  var xxKeyName = "MyTestKey1"
  var xxKeyValue = "12345"

   var oTableDataJson =
        JSON.stringify(
            {xxKeyName : xxKeyValue});
..
this result in a json looking like:
{"xxKeyName":"12345"}

but what I want is
{"MyTestKey1":"12345"}
LVL 2
Jayesh AcharyaTechnichal ConsultantAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jan LouwerensSoftware EngineerCommented:
Try:

var oTableDataJson = 
        JSON.stringify(
            {"name": xxKeyName, "value" : xxKeyValue});

Open in new window

0
Jan LouwerensSoftware EngineerCommented:
Another option is to create an object first, and dynamically set the fields:

var xxKeyName = "MyTestKey1"
var xxKeyValue = "12345"

var obj = {};
obj[xxKeyName] = xxKeyValue;

var oTableDataJson = JSON.stringify(obj);

Open in new window

1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Julian HansenCommented:
Just a sidebar because the question is misleading. JSON is a string representation of a JavaScript object - you cannot assign a key in JSON - you create the key in JavaScript and then stringify the result.

Then just a word or two on how JavaScript objects work
The left hand side (key) of an object declaration is the name of the key - you cannot specify a variable name - it will not be interpreted as such.

To assign a key dynamically you have to use Array notation (as Jan demonstrated in his second post). While this looks like an associative array has been created it is actually implemented as an object.

So
var x = {};
x['test'] = 12345;
console.log(x);

Open in new window


Will produce the following output
Object { test: 12345 }

Open in new window


What if we did this though
var y = [];
y['test'] = 'abc';

Open in new window

This creates something that is a bit of a mix. An array that also has properties
If we dump this it produces
[]
length: 0
test: "abc"
__proto__: Array []

Open in new window

If we add the following
y.push(1);

Open in new window

We get
[…]
0: 1
length: 1
test: "abc"
__proto__: Array []

Open in new window


So from this we can see that to generate a pure object with dynamic keys we declare the variable as an object first

var myObj = {}

Open in new window


And then use "array notation" to assign the key
var keyname = 'MyDynamicKey';
var value = '123';
myObj[keyname] = value;

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.