I am Cavic
I am Cavic

Reputation: 1085

Grab value of array(key:array(key:val)) dynamically

I have a calculation done that looks up values in my array of arrays with keys; what I am trying to accomplish is something like this.

Eg> If score value is 1 > go to array grab key 1 now there is second parameter which we can say total. Now we grab an array from the key 1 and from with in it we look for total key -> value.

It could look like this Score = 1 Total = 4 Value = ?

array 1:[1:3,2:6,3:19,4:55];

So result should return value 55.

var scores =[{1:[{value:'4'},{score:'1'},{css:'green'}]}];

To keep it simple i only used 1 key in outer array.

Also I used a loop to see how this plays out,

for (var key in scores){
    console.log(scores[key]);
    var arr = scores[key];
    for (var value in arr){
        console.log(arr[value]);
        var single = arr[value];
        for(var val in single){
            console.log(single[val]);
        }
    }
}

Final loops shows me the inner array with keys and values as Objects

Now I am wondering what would be the best and quickest way for me to get these values if I do something like

function getValue(Score, Total){
    alert("Key " + value + "is " + this); 
    alert("Key " + score + "is " + this); 
    alert("Key " + css + "is " + this); 
}

Thanks

Upvotes: 1

Views: 161

Answers (1)

keewnn
keewnn

Reputation: 600

You're overcomplicating things. You could just use something like this:

var scores = [
    {'value': 4, 'css': 'green'}, // This is key 0
    {'value': 9, 'css': 'yellow'} // This is key 1 etc
];

function getScoresValue( key, prop ) {
    return scores[key][prop];
}

// Example:

console.log(  getScoresValue(1, "css") ); // yellow

Upvotes: 4

Related Questions