在不知道数据密钥的情况下填充单元格
Populate cells without knowing the data key
我的数据是一个包含键值对的对象数组。我正在尝试用聚合物组件中的数据填充 table。如果我明确使用密钥,它就可以工作。这是 "FacilityId":
的示例
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<template is="dom-repeat" items="{{columns}}">
<th>{{item}}</th>
</template>
</tr>
</thead>
<tbody>
<template is="dom-repeat" items="{{data}}">
<tr>
<td>{{item.FacilityId}}</td>
</tr>
</template>
</tbody>
</table>
但是,正如您从动态生成的列中看到的那样,我并不总是知道键将被命名。我尝试使用 {{item[0]}}
但这不起作用,即使它起作用了我也不知道会有多少。我也尝试过使用嵌套模板,但我无法弄明白。
我的数据如下所示(同样,字段的数量和名称可能会有所不同):
根据@David R 引用的答案,这个有效:
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<template is="dom-repeat" items="{{columns}}">
<th>{{item}}</th>
</template>
</tr>
</thead>
<tbody>
<template is="dom-repeat" items="{{data}}">
<tr>
<template is="dom-repeat" items="{{_toArray(item)}}">
<td>{{item.value}}</td>
</template>
</tr>
</template>
</tbody>
</table>
以及来自 的自定义函数:
Polymer({
is: 'widget-table',
properties: {
data: {
type: Array,
value: function() {return []}
}
},
_toArray: function(obj) {
return Object.keys(obj).map(function(key) {
return {
name: key,
value: obj[key]
};
});
}
});
我的数据是一个包含键值对的对象数组。我正在尝试用聚合物组件中的数据填充 table。如果我明确使用密钥,它就可以工作。这是 "FacilityId":
的示例<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<template is="dom-repeat" items="{{columns}}">
<th>{{item}}</th>
</template>
</tr>
</thead>
<tbody>
<template is="dom-repeat" items="{{data}}">
<tr>
<td>{{item.FacilityId}}</td>
</tr>
</template>
</tbody>
</table>
但是,正如您从动态生成的列中看到的那样,我并不总是知道键将被命名。我尝试使用 {{item[0]}}
但这不起作用,即使它起作用了我也不知道会有多少。我也尝试过使用嵌套模板,但我无法弄明白。
我的数据如下所示(同样,字段的数量和名称可能会有所不同):
根据@David R 引用的答案,这个有效:
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<template is="dom-repeat" items="{{columns}}">
<th>{{item}}</th>
</template>
</tr>
</thead>
<tbody>
<template is="dom-repeat" items="{{data}}">
<tr>
<template is="dom-repeat" items="{{_toArray(item)}}">
<td>{{item.value}}</td>
</template>
</tr>
</template>
</tbody>
</table>
以及来自
Polymer({
is: 'widget-table',
properties: {
data: {
type: Array,
value: function() {return []}
}
},
_toArray: function(obj) {
return Object.keys(obj).map(function(key) {
return {
name: key,
value: obj[key]
};
});
}
});