Forum Discussion

JeromeVillani's avatar
JeromeVillani
Community Member
3 years ago

Javascript: get variable's value (number)

Hi there,

 

I'm 99% there on a javascript but am stumbling on how to extract the value behind a variable. A user creates 4 choices (%Choice1%....%Choice4&) and then clicks one of 4 buttons to add+1 to variables %Choice1_count%......%Choice4_count% (these are number variables). I then need to sort the variable in descending order.

My javascript array looks like this:

var myarray = [
{ key: Choice1, val: Choice1_count },
{ key: Choice2, val: Choice2_count },
{ key: Choice3, val: Choice3_count },
{ key: Choice4, val: Choice4_count },
]

It does work if I test it and replace Choice1_count...Choice4_count with actual numbers like below:

var myarray = [
{ key: Choice1, val: 5 },
{ key: Choice2, val: 4 },
{ key: Choice3, val: 6 },
{ key: Choice4, val: 2 },
]

but I am struggling to get the Javascript to read the number behind the variable %ChoiceX_count%. What I'm trying to get to is something like this:

var myarray = [
{ key: Choice1, val: get value of %Choice1_count% },
{ key: Choice2, val: get value of %Choice2_count% },
{ key: Choice3, val: get value of %Choice3_count% },
{ key: Choice4, val: get value of %Choice4_count% },
]

I'm sure there must be an easy way to do this?

Many thanks.

  • JeromeVillani's avatar
    JeromeVillani
    Community Member

    Please ignore, sorted with the below.

    var myarray = [
    { key: Choice1, val: player.GetVar("Choice1_count") },
    { key: Choice2, val: player.GetVar("Choice2_count") },
    { key: Choice3, val: player.GetVar("Choice3_count") },
    { key: Choice4, val: player.GetVar("Choice4_count") },

     

    It was a simple answer.

     

  • Thanks for sharing an update with the community, Jerome! I'm sure others will find this helpful. 

    Have a great start to your day! 

  • You are mixing Arrays and Objects. Although that is fine, it makes things more complicated to get selected. But solvable ofcourse...

    Like this....

    var player = GetPlayer();
    var myarray = [
    { key: 'Choice1', val: 5,},
    { key: 'Choice2', val: 4,},
    { key: 'Choice3', val: 6,},
    { key: 'Choice4', val: 2,}
    ];

    var selectedChoice = myarray.find(function (choice) {
    return choice.key === 'Choice3';
    });
    console.log(selectedChoice);
    player.SetVar("output","key: "+selectedChoice.key+" val: "+selectedChoice.val);

    Using the array.find functionality to find the proper Object... and because its an Object then using dot-syntax to select the values inside that Object.

    Ah, you were having trouble with getting the variable from the player...well my answer not relevant then...although you might find use for it.