[英]Polymer - Iterating over object in template
According to the polymer docs , an object or array can be iterated over using the repeat
statement in a <template>
: 根据聚合物文档 ,可以使用<template>
的repeat
语句迭代对象或数组:
"expression" can be a simple identifier, a path or a full expression (including Object and Array literals). “expression”可以是简单的标识符,路径或完整表达式(包括Object和Array文字)。
After testing, however, it seems as though the repeat statement only works with arrays, and not with objects: 但是,经过测试,似乎repeat语句只适用于数组,而不适用于对象:
http://jsbin.com/oqotUdE/4/edit http://jsbin.com/oqotUdE/4/edit
Am I doing something incorrectly? 我做错了什么吗?
I recently ran into this issue and got around it by using a filter which returns Object.keys(obj)
. 我最近遇到了这个问题并通过使用返回Object.keys(obj)
的过滤器解决了这个问题。 Below is a simple example of how to do so (maybe there is a much better way, if so, enlighten me please)... 下面是一个如何操作的简单示例(也许有更好的方法,如果有的话,请赐教)...
<template repeat="{{item in obj | getKeys}}">
<span>Key: {{item}}</span>
<span>Value: {{obj[item]}}</span>
</template>
...etc...
<script>
Polymer('my-element', {
// yes i know, instantiate arrays/objects in the created method,
// but this is just an example
obj : {},
// my custom filter function to use in looping objects
getKeys : function(o){
return Object.keys(o);
}
});
</script>
Of course you can get more complex, checking for data types and making sure its an object. 当然,您可以更复杂,检查数据类型并确保其对象。 Below is a recursive version that loops through infinite nested objects (again, if there is a simpler way, let me know) 下面是一个循环遍历无限嵌套对象的递归版本(再次,如果有更简单的方法,请告诉我)
<template if="{{obj}}" id="root" bind="{{obj as o}}">
<ul>
<template repeat="{{item in o | getKeys}}">
<li>
<span class="key">{{item}}</span>
<template if="{{o[item] | isNotObject}}">
<span class="value">{{o[item]}}</span>
</template>
<template if="{{o[item] | isObject}}">
<template ref="root" bind="{{o[item] as o}}"></template>
</template>
</li>
</template>
</ul>
</template>
...etc...
<script>
Polymer('object-view', {
obj : {},
getKeys : function(o){
return Object.keys(o);
},
isObject : function(v){
return typeof(v) === "object";
},
isNotObject : function(v){
return typeof(v) !== "object";
}
});
</script>
This certainly works (for me), to loop through objects ( and arrays , actually). 这对我来说肯定有用,可以循环遍历对象(实际上是数组 )。 Although, I'm not completely happy with the use of Object.keys
. 虽然,我对使用Object.keys
不是很满意。 I'll be very encouraged to see support for object iteration soon in polymer. 我将非常鼓励在聚合物中很快看到对对象迭代的支持。
The docs there are imprecise. 那些文档是不精确的。 The general nature of expressions is explicated but I don't believe it intends to say you can iterate over objects with repeat. 表达式的一般性质是明确的,但我不认为它打算说你可以重复迭代对象。
I believe only Arrays are support for iteration at this time, although there is talk of possibly supporting NodeLists also. 我相信目前只有Arrays支持迭代,尽管有人可能会支持NodeLists。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.