If I have a string of "myArray[0].myPrice", how do I turn this in to a reference to myPrice?
This is the code context:
binding.value = convert(binding.data[binding.field],
binding.converter, binding.data, elem);
binding.field is what contains “myArray[0].myPrice”.
binding.data has a reference to the hierarchical object which has an Array property of myArray, and the first element is an object with a property of myPrice.
EDIT: based on the answers, this worked:
binding.value = convert(eval('(binding.data.' + binding.field + ')'),
binding.converter, binding.data, elem);
Is it good to use eval like this? I thought eval was going away in newer JavaScript?
You can use
eval, but here is a better solution:A breakdown of what I’m doing here:
In JS any property can be called as
object[propertyName].That includes arrays, i.e.
a[3]is the same asa['3'].Therefore, we split the string using one of the characters:
.,[,]. The+is there because without it if you havea[3].b[3]the].will give you an emptystring.
We might get an empty string in the end, but that’s not a problem since
""is likefalsein JS.You could go further and filter out all the invalid variable names, which in javascript is a name that does not conform to
[a-zA-Z_$][0-9a-zA-Z_$]*. But I am not quite sure as to why one would do that…