微信小程序开发过程中,遇到这么一个状况:须要遍历对象的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>