Dynamic orderBy with JayData

Order the elements based on fields and orders in arrays

by JayData

HTML

<script src="http://include.jaydata.org/jaydata.js"></script>

JavaScript

//Define the Category entity with the Products array property
$data.Entity.extend("Category", {
    Id: { key: true, type: "int", computed: true },
    Name: { type: "string", required: true }
   
});


//Define our context to 
$data.EntityContext.extend("NorthwindContext", {
    Categories: { type: $data.EntitySet, elementType: Category, tableName: 'Cat2' }
});

//Initialize a WebSQL/SQLite database connection with the defined schema
var nw = new NorthwindContext({ provider: "webSql", databaseName: "northwind" });

nw.onReady(function () {
    var fields = ['Name', 'Id'];
    var order = ['ASC', 'DESC'];
    
    
    var q = nw.Categories;
    fields.forEach(function(fieldName, idx){
        /*
        if(order[idx] === 'ASC'){
            q = q.orderBy('it.'+fieldName);
        }
        else{
            q = q.orderByDescending('it.'+fieldName);
        }
        */
        //you can also use q.order('fieldName') and q.order('-fieldName')
        
        console.log(idx);
        var orderByField = (order[idx] === 'ASC') ? fieldName : ("-" + fieldName);
        console.log(orderByField);
        q = q.order(orderByField);
    });
    q.toArray($data.debug);
});