-1

I'm trying to use the object keys p1, p2, p3 as variable names, but my knowledge of javascript seems insufficient to get it right. How can I do this, so in the end console.log(p1) is value1 etc.

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " -> " + p[key]);
      var key = p[key]
    }
}

console.log(p1,p2,p3) //value1, value2, value3
Norman
  • 6,159
  • 23
  • 88
  • 141
  • 1
    This might be an X/Y problem. Why do you want to create the variable dynamically if you're going to statically reference it later? – Mike May 31 '20 at 20:05

2 Answers2

0

You can do this easily using the global window object like:

window[key] = p[key]

var p = {
  "p1": "value1",
  "p2": "value2",
  "p3": "value3"
};

for (var key in p) {
  if (p.hasOwnProperty(key)) {
    window[key] = p[key]
  }
}

console.log(p1, p2, p3)
palaѕн
  • 72,112
  • 17
  • 116
  • 136
-1

In fact, you are not allowed to overwrite an object property key. I assume that's your goal by reading the var key = p[key] line.

hblanco
  • 116
  • 7