0

I have a variable that consists structs. These structs can have CFBoolean variables, more structs, and other variables. In the beginning this was nested two levels deep. We are now moving up to four levels. I don't like my current approach. I could also imagine five levels happening. I have no control over the external system that needs this data. So I am looking for a more general approach.

function toJavaBoolean(any data){
    //for now, assume it's a struct to DBO conversion

    data.each(function(key, value) {
        if (getMetadata(data[key]).getName() == 'coldfusion.runtime.CFBoolean') {
            data[key] = javacast("boolean", data[key]);
        }

        if (isStruct(data[key]))    {
            data2 = data[key];
            data2.each(function(key, value) {
                if (getMetadata(data2[key]).getName() == 'coldfusion.runtime.CFBoolean')    {
                    data2[key] = javacast("boolean", data2[key]);
                }

                if (isStruct(data2[key]))   {
                    data3 = data2[key];
                    data3.each(function(key, value) {
                        if (getMetadata(data3[key]).getName() == 'coldfusion.runtime.CFBoolean')    {
                            data3[key] = javacast("boolean", data3[key]);
                        }

                        if (isStruct(data3[key]))   {
                            data4 = data3[key];
                            data4.each(function(key, value) {
                                if (getMetadata(data4[key]).getName() == 'coldfusion.runtime.CFBoolean')    {
                                    data4[key] = javacast("boolean", data4[key]);
                                }
                            });
                        }
                    });
                }
            });
        }
    });
James A Mohler
  • 11,060
  • 15
  • 46
  • 72
  • 1
    How do you handle NULL support? When exporting to CSV, I've been transforming yes/no to 1/0 while NULL (from an SQL query) is treated special & exported as an empty string. For JSON, you may desire to delete the key so it's undefined. – James Moberg Jan 27 '20 at 21:11

1 Answers1

3

You can use recursion like so...

function toJavaBoolean(any data){
    data.each(function(key, value) {
        if (getMetadata(data[key]).getName() == 'coldfusion.runtime.CFBoolean') {
            data[key] = javacast("boolean", data[key]);
        }
        else if (isStruct(data[key]))
            data[key] = toJavaBoolean(data[key]);
    }
    return data;
}

There are some non-recursive approaches that may be faster for larger sizes or great depths.

Dan Roberts
  • 4,664
  • 3
  • 34
  • 43