/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] Dynamic variable in if statement treated as string?

Hello.
I have an array named theData and an object named myData which is generated from the array. I need my for loop to enable/disable buttons on the page depending on the value of the var dollars vs the value of myData.selectionName.cost

This is what I have so far

[CODE]
function setButtonState(){
for (var i = 0; i < theData.length; i++){
var selection = theData[i].name;
var nameCombo = selection + “Button”;
var costCombo = “myData.” + selection + “.cost”;
if (dollars < costCombo){
$(“#” + nameCombo).prop(“disabled”, true);
} else {
$(“#” + nameCombo).prop(“disabled”, false);
}
}
}
[/CODE]

The only part that doesn’t work is the if statement. Currently it checks dollars vs the string inside costCombo. I would like to compare dollars vs myData.selection.cost where selection is dynamic and set earlier in the function based on our theData[i].name.

How do I get the if statement to read costCombo as myData.example.cost instead of “myData.example.cost”

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumFeb 01.2016 — If you write:
[CODE]var costCombo = "myData." + selection + ".cost";[/CODE]
you would have to use eval() to make it work. However I don't like eval (and many others don't either). Therefore I would recommend the following:
[CODE]var costCombo = myData[selection]["cost"];[/CODE]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
Copy linkTweet thisAlerts:
@BillMurrayauthorFeb 01.2016 — Works perfectly. Thank you!
×

Success!

Help @BillMurray spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...