red
red

Reputation: 305

Add quotations to a key in JavaScript

Let's say I have this code:

var testObjs = ['This is One Test', 'A Sapphire Road', 'Ragon Done 12'];
var sampleAnswer = ['Hello', 'World', '123'];

var complexObj = {};

for (var i = 0; i < testObjs.length; i++) {
  complexObj[testObjs[i]] = sampleAnswer[i];
}

console.log(complexObj);

This creates an object with a value. Both are dynamically created and thus, we have this object:

{
    A Sapphire Road: "World"
    Ragon Done 12: "123"
    This is One Test: "Hello"
}

As you can see, the problem is that there is no double quotations. I want it to be like this (so it is valid):

{
    "A Sapphire Road": "World"
    "Ragon Done 12": "123"
    "This is One Test": "Hello"
}

How would I go about doing it?

Upvotes: 1

Views: 860

Answers (3)

The Witness
The Witness

Reputation: 920

Last line:

console.log(JSON.stringify(complexObj));

Results with:

{"This is One Test":"Hello","A Sapphire Road":"World","Ragon Done 12":"123"}

But don’t bother with console.log result. This is presented without quotation marks only to you in console, for your convienience. In reality this is more like object in computer memory.

But if you need it to pass it in form you requested, stringify it with JSON.

Upvotes: 3

Xetnus
Xetnus

Reputation: 353

As Josh said, nothing's wrong with your current code. However, if you still want to see quotation marks with it, try this:

for (var i = 0; i < testObjs.length; i++) {
  complexObj["\"" + testObjs[i] + "\""] = sampleAnswer[i];
}

Upvotes: 0

Josh Beam
Josh Beam

Reputation: 19792

It is correct. It's just showing without the quotes in the console. See the jsbin. No errors.

Upvotes: 2

Related Questions