Wednesday, September 22, 2010

JSON Fetch Random Record

Searched everywhere for this one. Hopefully it will help someone else out...

I was looking for a way to filter a JSON dataset by an ID number. Here goes...


  1. Step 1 : Create your JSON Data.


    var item = [
    { "id": "0", "language": "English"},
    { "id": "1", "language": "Spanish"},
    { "id": "2", "language": "French"},
    { "id": "3", "language": "Hungarian"}
    ];

  2. Step 2 : Function to find Unique Value:


    I cant take credit for this one. I found this at : http://stackoverflow.com/questions/604935/how-can-i-filter-json-for-unique-key-name-value-pairs. Here it is...

    function getDistinct(o, attr) {
    var answer = {};
    $.each(o, function(index, record) {
    answer[index[attr]] = answer[index[attr]] || [];
    answer[index[attr]].push(record);
    });
    return answer;
    }

  3. Step 3: Create Random Number

    var randNo = Math.floor(Math.random() * 4); (with 4 being the same number of records contained in the JSON Dataset).

  4. Step 4: Return unique record items


    $(function() {
    $.each(getDistinct(markers, "id"), function(groupName, recordArray) {
    var firstRecord = recordArray[randNo];
    $('
  5. ').html(firstRecord.language).appendTo('#results');
    });
    });




Finally, the body simply contains an unordered list with an id of results to contain the information.

0 comments: