سؤال

I am trying to handle a simple case where i could be getting an object, or a dictionary. So i am either going to get a object like:

obj.fields.nick

or its going to be a dictionary like

obj['nick']

I was wondering if there was a simpler way to do the following:

value = (eval("obj.fields." + field[1]) if obj?.fields ) ? eval("obj['#{field[1]}']")

I was hoping to do something like:

value = (obj?.fields?."#{field[1]}" ) ? eval("obj['#{field[1]}']")  

But if that worked I wouldn't be writing this post...

I am basically looking for a way to execute a string as part of the if

هل كانت مفيدة؟

المحلول

value = obj.fields?[field] ? obj[field]
# or
value = (obj.fields ? obj)[field]

This is the same as

if obj.fields?
    obj.fields[field]
else
    obj[field]

There is absolutely no need for eval.

نصائح أخرى

The string interpolation construct ("Equals four: #{2+2}") is something that is handled by the coffeescript compiler, and will therefore not work inside an eval. But assuming the naming of the stuff inside the string does not change, you could easily rewrite it, so that eval("obj['#{field[1]}']") becomes eval("obj['"+field[1]+"']"). Assuming I got your question right of course.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top