Quantcast
Channel: ColdFusion – ColdFusion
Viewing all articles
Browse latest Browse all 100

Converting an array of structs to a query dynamically

$
0
0

I was working with some JSON data in Javascript and wanted to view the data in a table layout so I could quickly scan it to see what I was working with. This is easily done in a browser using console.table. For example, using the following Javascript code:

// Javascript
data = [
    { i: 1, label: "One" },
    { i: 2, label: "Two", foo: "Foo" },
    { i: 3, label: "Three", bar: "Bar" },
    { i: 4, label: "Four", foo: "Foo", bar: "Bar" }
];

console.table(data);

I get a nice compact view of the data in my browser console:

output from console.table(data)

This got me thinking about how you could dump out an array of structs in a compact form using CFML.

Here’s what the standard dump of that array in CFML looks like:

writedump of array of structs

Not too bad to read, but as we get more rows and/or more keys, it’s going to get much harder to visual scan.

I decided that a dump of CFML’s query object is essentially what we are after, so just need to convert the array to a query. As each element in the array has different keys, this needs to be done dynamically. Here’s what I came up with:

// CFML
data = [
    { i: 1, label: "One" },
    { i: 2, label: "Two", foo: "Foo" },
    { i: 3, label: "Three", bar: "Bar" },
    { i: 4, label: "Four", foo: "Foo", bar: "Bar" }
];
  
function arrayToQuery(data) {
    return data.reduce(function(accumulator, element) {
        element.each(function(key) {
            if (!accumulator.keyExists(key)) {
                accumulator.addColumn(key, []);
            }
        });
        accumulator.addRow(element);
        return accumulator;
    }, QueryNew(""));
}

// writeDump(data);
writeDump(arrayToQuery(data));

The output from this looks like:

writedump of array as query

I’m not intending to use this code in production, it was more of a coding exercise, but thought I’d share.

Runnable code here if you want to hack about with it.
https://cffiddle.org/app/file?filepath=d3656d85-050d-4a86-b26f-9797073991d9/3688841c-1312-47b4-9f85-00880b379a54/7c2c9541-cf21-4ff0-9795-7dcda91b963b.cfm

The post Converting an array of structs to a query dynamically appeared first on ColdFusion.


Viewing all articles
Browse latest Browse all 100

Trending Articles