0

I want to create an object some thing like this

var key = "key";
var obj={};
obj[key] = "value";

My required output is

{ "key":"valie"}

Key type must be string because i have keys like #12:5 , #12:89 ( orientDB ids ). REASON:- Because embeddedList of orientDB is not accepting any key without quotes.
Thanks

1
  • Will there be nested objects? Commented Apr 15, 2015 at 21:02

3 Answers 3

3

You're probably looking for JSON syntax.

Here's output from my console.

var key = "key"; //var not Var
var obj={}; //same here
obj[key] = "value";
"value"
obj
Object {key: "value"} //key is not in quotes, need to stringify!
JSON.stringify(obj);
"{"key":"value"}"
Sign up to request clarification or add additional context in comments.

Comments

1

Object literals in javascript can be declared with quoted keys:

{
  "Okeli-dokeli": "Flanders",
  "Doh!": "Simpson!"
}

You can also dynamically assign values to a key in javascript with the bracket syntax:

var x = {};
x["A B C"] = "foo";

ADDED:

The JSON format is based on a subset of javascript but has object keys which are always quoted. Therefore converting any javascript object to JSON will "stringify" the keys:

> JSON.stringify( { a : 'b' } )
> "{"a":"b"}"

Comments

0

In the off chance you are not expecting nested objects, this can easily work as well:

var key = "key";
var obj={};
obj[key] = "value";


var s = "{\r\n";
for (var p in obj) s+= '    "'+p+'": "' + obj[p] + '"\r\n';
s += "}\r\n";

Also, it's var, not Var (no capital first letter).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.