Access Array with String key Access Array with String key json json

Access Array with String key


As simple as that:

const mydata = data[ keylist[1] ];

Also, your code is correct from the point of syntax, but it tells completely different than you expect it to tell.

data.keylist[1];

tells JS that you expect to have an object called data which has a property called keylist and which is (most likely) type of array, and you want to get the second element of this array.

PS: And one more point here. Your question title is not completely correct because of the difference between Arrays and Object in JS.

There is no "string keys" for arrays in JS, so you cannot "access array with a string key". Well, truly speaking there are, but not for items of array. Array items only have numeric index, which you can use to access it. Objects, in contrast to arrays, may have named properties. So when you see something like that: data = myVar['data'], you can tell that you're dealing with an object, while data = someVar[0] can be both, an Array (most likely) or also an Object with key named '0'.


I don't think the issue you're having with your first example is because it returns a key. I believe the issue is because data doesn't have a property called keylist. Instead of that, try it as

data[keylist[1]]

and see if that works for you. The reason this one should work is that, in this situation, Javascript will evaluate the string return of keylist[1] and then use it as a string index for the data variable. Let me know if this works out for you :D


You can try using using something like this.

data[keylist[1]]