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.
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.
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'
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.
Look:
var a = "p", b = "q", c = "r";
var obj = {[a] : "x", [b]: "y", [c]:"z"};
console.log(obj);
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);