charlie_cat
charlie_cat

Reputation: 1850

How to get corresponding value of key in JavaScript

I have this code:

var getValuesArray = [];
var setValuesArray = [];


function SetValueJson(key, value, scormVersion, methodCalled)
{
   if (key1 != null) {
     var obj = {
      key: key1,
     value: value1
   }
   setValuesArray.push(obj);
   alert("pushing the key as: " + setValuesArray[key] + " and value as: " + setValuesArray[key].value); //not shure how te reference it?
   return value;
}

and:

function GetValueJson(key, scormVersion, methodCalled) {
   //I will get to this later, want to get the array right first

}

How do I reference the array?alert("pushing the key as: " + setValuesArray[key] + " and value as: " + setValuesArray[key].value); is not correct..

thanks

Upvotes: 1

Views: 3613

Answers (2)

Anoop
Anoop

Reputation: 23208

I suggest you to use Object instead of Array.

Modified code

var setValuesArray = {};

function SetValueJson(key, value, scormVersion, methodCalled)
{
    setValuesArray[key]= value;

alert("pushing the key as: " + key + " and value as: " + value); return value; }

function GetValueJson(key, scormVersion, methodCalled) {
          return setValuesArray[key]; // will return 'undefined' if key is not present.
}

Upvotes: 2

Mutahhir
Mutahhir

Reputation: 3832

Well, this basically depends on what you want to do with this data structure.

If keeping these keys and values sequentially and their order is important than you would need to store them in an array.

If you only need to look up the values based on keys, then a simple object would do just fine.

Lets say you need to maintain the order of the key-value data as it comes in, and you're using an array for that, then you have two options:

  1. Keep the actual key-value store inside an object. For the order, maintain a separate array only keeping the keys. Here's what it should look like somewhat

    var keyValueStore = {},
        keyOrderStore = [];
    
    function store(key, value) {
        keyValueStore[key] = value;
        keyOrderStore.push(key);          
    }
    
    function getValueByIndex(index) {
        // do some bounds checking ofcourse :)
        return keyValueStore[keyOrderStore[index]];
    }
    
    function getValue(key) {
        return keyValueStore[key];
    }
    
  2. This is in my opinion a better option. However, if you don't want to maintain and sync two separate data structures, you can use this:

    var storage = [];
    
    function store(key, value) {
        storage.push({
            key: key,
            value: value
        });
    }
    
    function getAtIndex(index) {
        return storage[index].value;
    }
    
    function getValue(key) {
        for (var i = storage.length-1; i >= 0; i--) {
            var obj = storage[i];
            if (obj.key === key) return obj.value;
        }
    }
    

Hope this helps.

Upvotes: 0

Related Questions