将动态表从行转换为列,反之亦然

时间:2017-04-27 09:27:23

标签: javascript html angularjs

config.previewData = [
    {
        Cartridges:27989,
        Total Accounts:294,
        Metrices:"MVC",
        Toner Cartridges:5928,
        INK Cartridges:22061
    },
    {
        Cartridges:56511,
        Total Accounts:376,
        Metrices:"SMB",
        Toner Cartridges:15253,
        INK Cartridges:41258
    },
    {
        Cartridges:84,500,
        Total Accounts:670,
        Metrices:"Grand Total",
        Toner Cartridges:21,181,
        INK Cartridges:63,319
    },
]

和我这样的HTML代码

<table class="table table-striped">
    <thead>
        <tr role="row">
            <th data-ng-repeat="(key, val) in config.previewData[0]">
                {{ key}}
            </th>
        </tr>
    </thead>

    <tbody>
        <tr data-ng-repeat="row in config.previewData">
            <td data-ng-repeat="column in row">
                {{column}}
            </td>
        </tr>
    </tbody>
</table>

此代码将打印完美,如下图所示 enter image description here

现在我想将此表转换为行到列和列到行。 动态表是否可行,因为我的对象是动态的而不是固定的。

如果有人知道怎么做,请帮助我。 转置表后看起来像这样 enter image description here

3 个答案:

答案 0 :(得分:2)

使用您的示例代码所做的相同假设(即config.previewData始终包含至少一个对象,并且所有对象具有相同的属性...)

<table class="table table-striped">
    <tbody>
        <tr data-ng-repeat="(key, val) in config.previewData[0]">
            <th>
                {{ key }}
            </th>
            <td data-ng-repeat="row in config.previewData">
                {{ row[key] }}
            </td>
        </tr>
    </tbody>
</table>

答案 1 :(得分:1)

使用reduce,您可以使用这样的内容来转置数据,然后可以非常轻松地使用ng-repeat进行迭代!

示例代码段(在纯JS中用于简化):

&#13;
&#13;
var previewData = [{
    "Cartridges": 27989,
    "Total Accounts": 294,
    "Metrices": "MVC",
    "Toner Cartridges": 5928,
    "INK Cartridges": 22061
  },
  {
    "Cartridges": 56511,
    "Total Accounts": 376,
    "Metrices": "SMB",
    "Toner Cartridges": 15253,
    "INK Cartridges": 41258
  },
  {
    "Cartridges": 84500,
    "Total Accounts": 670,
    "Metrices": "Grand Total",
    "Toner Cartridges": 21181,
    "INK Cartridges": 63319
  }
]

var transpose = previewData.reduce(function(arr, obj) {
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      arr[key] = arr[key] || []
      arr[key].push(obj[key])
    }
  }
  return arr
}, {})

console.log(transpose)
&#13;
&#13;
&#13;

答案 2 :(得分:0)

这是我能想到的唯一(肮脏)方式

<tr>
        <td data-ng-repeat="row in previewData">{{row['Metrices']}}</td>
    </tr>
    <tr>
        <td data-ng-repeat="row in previewData">{{row['Total Accounts']}}</td>
    </tr>
    <tr>
        <td data-ng-repeat="row in previewData">{{row['Toner Cartridges']}}</td>
    </tr>

......等等

其他选项:Transposing JSON