1

I have a object

let x = { "propName": "response" }

Is there a way we can change the key name for the object. I would like to pass an index for the propName like

{ "prop1Name": "response" }

Is there a way to do this, I know I cant do it like this but, I tried it with

var obj = { "prop"+i+"Name": "response" };
console.log(obj);

But, it failed ofcourse. Is there a way to do it?

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
amar
  • 443
  • 4
  • 15
  • 1
    Does this answer your question? [JavaScript set object key by variable](https://stackoverflow.com/questions/11508463/javascript-set-object-key-by-variable) – wp78de Nov 04 '20 at 21:59

1 Answers1

3

You can use the new ES6/Babel syntax of {[keyfromvariable]:"value"}, so, in your case...

var i = "1";
var obj = { ["prop"+i+"Name"]: "response" };
console.log(obj);

If you don't have ES6/Babel as an option, you can define the object first and then use []...

    var i = "1";
    var obj = {};
    obj ["prop"+i+"Name"] = "response" ;
    console.log(obj);
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133