Tuesday, October 18, 2011

Convert JavaScript object to Associative Array

Hello,

This is small post about converting JavaScript object to  associative array. Recently I was working on a project where I need to iterate through dynamic object. In short I have to create enumeration  for a dynamic object.  Object was dynamic so that all the properties of object were unknown. Following is the function to convert a JavaScript object to JavaScript associative array.

function toArray(_Object){
       var _Array = new Array();
       for(var name in _Object){
               _Array[name] = _Object[name];
       }
       return _Array;
}

So if you have any JavaScript object that can be converted to associative array using above function. New array will have all the object properties as keys and it's values as values and same way we can convert JavaScript associative array can be converted to JavaScript object.

function toObject(_Array){
       var _Object = new Object();
       for(var key in _Array){
              _Object[key] = _Array[key];
       }
       return _Object;
}

Above function will convert JavaScript associative array to Object. New object will have all keys in arrays as property and it's values as values of property.

Hope this will be helpful for you.

4 comments:

  1. Thanku Very Much.
    This is best Programm

    ReplyDelete
  2. This is not a associative array, just a flat array converter.

    This will NOT work:

    var obj = {
    "key1" : "value1",
    "key2" : {
    "key2a" : "value2a",
    "key2b" : "value2b"
    }
    };

    toArray ( obj );

    ReplyDelete
    Replies
    1. Your code show a JSON object, no a javascript Object.
      JavaScript:
      var obj = {
      key1 : "value1",
      key2 : {
      key2a : "value2a",
      key2b : "value2b"
      }
      };

      Delete
  3. dude your function is creating another object inside an array...

    ReplyDelete