Converting an array of structs to a query dynamically
An exercise in converting an array of structs to a query dynamically so you can dump out the data in a compact form
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:
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:
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:
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
Very nice thinking outside the box! This will be handy, thanks! 🙂
Yes, very nice. Thanks, John (aka poor yorik. “Alas”, I wonder how many get the quip in your “alias”!)
About the code, I hope you’ll submit it to the cflib site (cflib.org). Folks do still search there for possible CFML solutions to problems.Â
You’ll see a link there for submitting content, and indeed it’s now hosted on github (so submissions are by PR to that now). Ray is still the project owner, and though there are a couple of PRs outstanding from 2017, it’s worth a shot to see if it would get posted.
Thanks of course for the cffiddle.org link, in the meantime.
Hi Charlie,
Happy to add it to cflib – looks like it’s a Jekyll site now so will have to find some time to figure that out!
Simple and elegant. Â Great use of arrayReduce().
You must be logged in to post a comment.