Home > other >  Is there a way to store object accessors as variables in Javascript?
Is there a way to store object accessors as variables in Javascript?

Time:02-03

I have a script that I'd like to re-use for different projects where I'm calling similar APIs but the JSON object that I receive might be a little different. So, when I parse the data, I'd like to have control over what values I access.

For this particular API, the following works:

var contractData = theParsedJSONdata.data.items;

Going forward the keys data and items may vary. Can I use variables to access the object?

I tried this, but it didn't work:

let objectString = ".data.items";
var contractData = theParsedJSONdata   objectString;

Example data:

    { data: 
   { address: '0x000000000222221111111111',
     updated_at: '2022-02-03T00:30:12.793596926Z',
     next_update_at: '2022-02-03T00:35:12.793597076Z',
     quote_currency: 'USD',
     chain_id: 137,
     items: 
      [ [Object],
        [Object],
        [Object],

CodePudding user response:

Use a function.

let objectAccessor = obj => obj.data.items;
let contractData = objectAccessor(theParsedJSONdata);

You can later reassign objectAccessor:

objectAccessor = obj => obj.something.thing;

CodePudding user response:

You can use variables as object keys with this notation:

key1 = "data";
key2 = "items";

obj[key1][key2] // equivalent to obj.data.items
  •  Tags:  
  • Related