Pawan
Pawan

Reputation: 32331

How to create key value pair JSON array

I have an array as shown below from which i am trying to create a key value

var text = ["One","TWO","THREE"];

var myarray = [];

$( document ).ready(function() {
for(var i=0;i<text.length;i++)
{
var name = text[i];
var toaddstr = 'CNX'
myarray.push(name+":"+toaddstr);
}
console.log(myarray);
});

When i run the above program the output i am getting is

["One:CNX", "TWO:CNX", "THREE:CNX"]

IS it possible to create an array as this way

[
"One": "CNX",
"TWO": "CNX",
"THREE": "CNX"
]

This is my fiddle , please let me know how to do this

http://jsfiddle.net/cod7ceho/424/

Upvotes: 0

Views: 11216

Answers (3)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

The following format:

[
"One": "CNX",
"TWO": "CNX",
"THREE": "CNX"
]

Is not a valid one. It should be:

{
  "One": "CNX",
  "TWO": "CNX",
  "THREE": "CNX"
}

To do that:

var text = ["One", "TWO", "THREE"];

var myarray = {};

for (var i = 0; i < text.length; i++) {
  var name = text[i];
  var toaddstr = 'CNX'
  myarray[name] = toaddstr;
}
console.log(myarray);

Upvotes: 1

Nicolas
Nicolas

Reputation: 1870

You should use an object (which is a JS map), not an array. See your new code below.

var text = ["One","TWO","THREE"];

var myarray = {};

$( document ).ready(function() {
for(var i=0;i<text.length;i++)
{
var name = text[i];
var toaddstr = 'CNX'
myarray[name] = toaddstr;
}
console.log(myarray);
});

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337590

The format you're trying to create is not syntactically correct, you can't have key/value pairs in an array. However, you could use an object instead:

var obj = {};
["One", "TWO", "THREE"].forEach(function(v) {
  obj[v] = 'CNX';
});
console.log(obj);

Upvotes: 4

Related Questions