How do I change the return format of Slate queries from column to row?

256 views Asked by At

The results of my query look like:

{
  col1: [values],
  col2: [values]
}

Is there a way to get my query to return as a list of rows objects?

1

There are 1 answers

0
Adil B On

The best way is to write a function to convert your query response.

One example:

function transformColumnSchemaToRowSchema(data) {
    var keys   = _.keys(data);
    var arrays = _.values(data);
    
    
    var arrayOfPropertyLists = _.zip.apply(_, arrays);
    
    
    var arrayOfObjects = _.map(arrayOfPropertyLists, function(list) {
    var obj = {};
    
    
    _.each(keys, function(key, i) {
    obj[key] = list[i];
    });
    
    
    return obj;
    });
    
    
    return arrayOfObjects;
}

Or a more compact version:

var data = {{q_some_query}};
delete data['_response']
var newdata = _.zip.apply(_, _.values(data)).map((val) => _.zipObject(_.keys(data), val));

After you convert to this format, you might want to convert back to the original format (for example, if you want to put the data into a table widget in Slate). This is how that can be done:

var original_fmt = {};
_.forEach(_.keys(newdata[0]), function(k) {
original_fmt[k] = _.map(newdata, k);
});
// use original_fmt