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.

Saturday, October 1, 2011

Select Item in sencha touch list on load

Hello,

Recently I was working on Sencha Touch application. Requirement was to populate list and select a specific item which was selected by user earlier.

Following is the trick to do it.


myList.on('refresh', function(){
       var recordIndex = myList.store.find('field', 'value');
       myList.select(recordIndex,true,false);  
});


myList.store.find returns the index of record that matches the filters and it will be first match of record. So if you have multiple records with same value in field this will not be useful for you. You must need some unique value.

myList.select will select record in specific index. Second argument is to keep existing selection. In case of multiselect list this will preserve last selection and. Third argument is to suppress the slectionChange event. Sometimes you might have disclosure set on list. So might want to suppress the selection change.

Here select function also accept record or records instead of index. If you have record which were selected earlier, you can directly pass those records in select function as follow.

myList.select(records,true,false);

This is how you can select and item in sencha touch list.