微信小程序开发过程中,遇到这么一个状况:须要遍历对象的 key-value,而后渲染到视图中。
1,数据如下:
const PUBLIC_COURSE_CHOICE_ITEMS = {
math: {
subject: '数学',
children: [{ id: 1, title: '数一'},
{id: 2, title: '数二'},
{id: 3, title: '数三'},
{id: 0, title: '待定'}
]
},
english: {
subject: '英语',
children: [{ id: 4, title: '英一'},
{id: 5, title: '英二'},
{id: 0, title: '待定'}
]
},
politics: {
subject: '政治',
children: [{ id: 6, title: '政治'}
]
}
};
2,设置 wx:for 的 index 为 key,即指向对象的 key,通过 key-value 的形式进行取值
<view class="public-course-item"
wx:for="{{publicCourseItems}}"
wx:for-index="key"
wx:key="publicCourseKey">
<view class="public-course-subject">{{item.subject}}</view>
<view class="public-course-subject-children">
<view class="public-course-child"
wx:for="{{item.children}}"
wx:key="publicCourseChild"
data-key="{{courseIndex}}"
data-subject="{{key}}"
data-id="{{item.id}}"
catchtap="onChoicePublicSubjectHandle">
<text class="sue-icon sue-icon-radio{{courseItem.public_detail[key] == item.id ?'-checked':'' }}"style="margin-right: 14rpx;"></text>
{{item.title}}
</view>
</view>
</view>
3,渲染成果