json - Access value from JavaScript object via array-string -
my problem have json-object , array here example.
var object = { 'items':['entry1','entry2'] } i want access 'entry2' on constant string receive , shouldn't changed.
var string = 'items[1]'; the way i'm solving problem on eval function...
eval('object.'+string); this returns me entry2.
is there other way achieve without using eval()? object[string] or object.string
supposing string same form, extract parts using regex :
var m = string.match(/(\w+)\[(\d+)\]/); var item = object[m[1]][+m[2]]; explanation :
the regex builds 2 groups :
(\w+) : string \[(\d+)\] : digits between brackets and groups @ index 1 , 2 of array returned match.
+something parses number. it's not strictly needed here array accepts string if can converted find code more readable when conversion explicited.
Comments
Post a Comment