【问题标题】:converting array of nested structure to query将嵌套结构数组转换为查询
【发布时间】:2020-08-27 17:08:43
【问题描述】:

我正在从结构数组转换为查询,工作正常,但在我有一个数组和嵌套结构的情况下,我有点迷失了我应该在函数中修改什么来获取更改数据的查询。

我有以下代码

<cfscript>
data = [
    {"1" :
        { i: 1, label: "One" }
    },
    {"2" :{ i: 2, label: "Two", foo: "Foo" }},
    {"3" :{ i: 3, label: "Three", bar: "Bar" }},
    {"4" :{ i: 4, label: "Four", foo: "Foo", bar: "Bar" }}
];
  
function stackoverflow(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); abort;
writeDump(arrayToQuery(data));
</cfscript>

如果它是一个简单的 ArrayofStructs,上面的方法是有效的,但是一旦我添加了一个结构级别,它就会停止工作

【问题讨论】:

    标签: coldfusion lucee


    【解决方案1】:

    为什么不先将嵌套数组格式化为更简单的数组格式,然后再进行归约,就像这样。总会有更好的解决方案,但这一切都取决于您应用中的业务逻辑。

    <cfscript>
      data = [
          {"1" :{ i: 1, label: "One" }},
          {"2" :{ i: 2, label: "Two", foo: "Foo" }},
          {"3" :{ i: 3, label: "Three", bar: "Bar" }},
          {"4" :{ i: 4, label: "Four", foo: "Foo", bar: "Bar" }}
      ];
      function arrayToQuery(data) {
        return data.map(function(datum, index){
            return datum[index];
          }).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));
    </cfscript>
    

    【讨论】:

      猜你喜欢
      • 2021-02-09
      • 1970-01-01
      • 2014-10-13
      • 1970-01-01
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      相关资源
      最近更新 更多