0

So, I would like to edit a key in a JSON file in Node.js, where the key is specified in a variable.

For example, I have a var x = "y", (example variable for easier understanding) and I would like to edit a key in servers.json by the name of y, however, when I specify servers.x, it edits the key 'x', instead of 'y'. Of course, this is expected, there is nothing wrong with this, however I don't know how I can use the variables contents as the key name. Here is my code for easier understanding:

const servers = require('./servers.json');
var x = "y";
servers.x = "blah";

I would like my servers.json file to look like this:

{"y" : "blah"}

Instead it looks like this:

{"x" : "blah"}

How can I use the variable x's contents as the key name?

Thanks

2 Answers2

1

you can use ["object name"] instead

const servers = require('./servers.json');
var x = "y";
servers[x] = "blah";
Josh Stevens
  • 3,943
  • 1
  • 15
  • 22
0

servers[x] = "blah";

You are welcome

libik
  • 22,239
  • 9
  • 44
  • 87