How to sort array on key value in javaScript using Prototype library

We  can sort a JSON  array using this method:

  1. This is the method to sort the array:
    Array.prototype.sortOn = function(key){
        this.sort(function(a, b){
            if(a[key] < b[key]){
                return -1;
            }else if(a[key] > b[key]){
                return 1;
            }
            return 0;
        });
    }
    
    
  2. How to sort the array with data? Just do:
    var arr = [{name:'bob', artist:'rudy'},{name:'johhny', artist:'drusko'},{name:'tiff', artist:'needell'},{name:'top', artist:'gear'}];
    arr.sortOn("name");
    arr.sortOn("artist");

If we want to convert the array to JSON we have to do this:

  1. var array = [];
    for ( var i=1 ; i< arr.length; i++ ){
            var mComponente = {
    	        name	: 'bob',
    	        artist  : 'rudy',
    	};
            array.push(mComponente);
    }
    
    // convert array into JSON array
    var jsonArray = $.parseJSON(JSON.stringify(array));
    

Reference link: http://stackoverflow.com/questions/16648076/sort-array-on-key-value

Advertisements

jQuery form autofill

Simply autofill an empty form using JSON data:

  1. We need a form:
    <form id="f">
        name <input type="text" name="name">
        email <input type="text" name="email">
        love jQuery
        <input type="radio" name="lovejquery" value="yes"> yes
        <input type="radio" name="lovejquery" value="no"> no
    </form>
  2. and data:
    var data = {
        "name": "John Doe",
        "email": "johndoe@mail.com",
        "lovejquery": "yes"
    }
  3. How to autofill the form with data? Just do:
    $("#f").autofill( data );

Reference link: http://labs.creative-area.net/jquery.formautofill/doc/