0

in JavaScript I declared this var a = "p", b = "q", c = "r";

and var obj = {a : "x", b: "y", c:"z"};

and I want var obj = { "p": "x" , "q": "y", "r": "z"}

but I am not getting the same.

Ngoan Tran
  • 1,507
  • 1
  • 13
  • 17
Saurav kumar
  • 407
  • 2
  • 5
  • 11

4 Answers4

2
var obj = {};
obj[a] = "x"; // is what you want.
//Or
obj = {[a]: "x"}

variables cannot be evaluated for keys unless you directly point to it like above.

var obj = {a: "x"}; // evaluates the a as a string key name of 'a'
matt
  • 1,680
  • 1
  • 13
  • 16
2

You can either use a computed property like this:

var obj = {[a]: "x", [b]: "y", [c]: "z"}

or you can use obj[a] as other's have suggested which means use the value in a as the name of the key.

Note: computed properties won't have support in every environment. See the "Browser Compatibility" section in the link I posted above.

jakeehoffmann
  • 1,364
  • 14
  • 22
0

Look:

var a = "p", b = "q", c = "r";
var obj = {[a] : "x", [b]: "y", [c]:"z"};

console.log(obj);
0

Code

var a = "p", b = "q", c = "r";
var obj = {a : "x", b: "y", c:"z"};

function getObj(obj){
   var scope = this;
   var result = {};
   for(var key in obj){
      result[eval(key)] = obj[key];
   }
   return result;
};
var requiredObj = getObj(obj); 

//result - Object {p: "x", q: "y", r: "z"}
console.log(requiredObj);
Community
  • 1
  • 1
karthick
  • 5,998
  • 12
  • 52
  • 90