Reputation: 23
I have several json vars with the name of "jsonObject_" + id
, for example:
var jsonObject_123 = ...;
var jsonObject_456 = ...;
etc. All those jsons have the same format, same keys, but different values.
I also have a method that receives the id as argument.
I need to change the correct jsonObject address according to the id. That is, if the argument is 123
, I need to change jsonObject_123.address
How can I get the reference to jsonObject_123
based on the id argument?
Upvotes: 2
Views: 73
Reputation: 1038880
First a small remark about the terminology used here. What you are calling JSON vars has nothing to do with JSON. Those are plain javascript variables. JSON is a serialization format.
Now depending on the scope where those variables are defined you could use the following:
var id = '123';
window['jsonObject_' + id].address = 'some address';
In this example I have assumed that those variables are declared in the global scope => you could access them through the window
object. You will have to adapt this code depending on your specific case.
But a better approach would be to group all those variables into a containing object:
var jsonObject = {};
jsonObject['123'] = { address: 'address 1' };
jsonObject['456'] = { address: 'address 2' };
...
and then when you want to access it:
jsonObject['123'].address = 'some new address';
Upvotes: 4