如何用Vue.js解析Elasticsearch输出的嵌套JSON中的数组?
解决Vue解析Elasticsearch嵌套数组的问题
没问题!你已经成功处理了外层的hits数组,接下来只需要在每个person的循环中嵌套遍历inner_hits里的二级hits数组就行,这在Vue里用v-for嵌套就能轻松实现。
核心思路
你的Elasticsearch返回结构中,每个person对象的inner_hits.top_hits.hits.hits是一个合同数组,我们只需要在遍历person的<li>内部,再添加一个循环来遍历这个数组。
修改后的代码示例
<ol> <!-- 遍历外层的人员数组 --> <li v-for="(person, index) in people" :key="index"> <!-- 人员基本信息 --> <div>{{ person._source.name }} | {{ person._source.address }} | ID: {{ person._source.person_id }}</div> <div>关联合同总数: {{ person.inner_hits.top_hits.hits.total }}</div> <!-- 遍历嵌套的合同数组 --> <ul style="margin-left: 20px; margin-top: 8px;"> <li v-for="(contract, contractIndex) in person.inner_hits.top_hits.hits.hits" :key="contractIndex"> <div>合同ID: {{ contract._id }} | 发布年份: {{ contract._source.pub_year }}</div> <!-- 遍历合同的keywords数组 --> <div>关键词: <span v-for="(keyword, kwIndex) in contract._source.keywords" :key="kwIndex"> {{ keyword }}<span v-if="kwIndex < contract._source.keywords.length - 1">, </span> </span> </div> </li> </ul> </li> </ol>
关键细节说明
- 嵌套循环的路径:一定要注意Elasticsearch的嵌套结构,合同数组的完整路径是
person.inner_hits.top_hits.hits.hits(没错,是两层hits,第一层是包含total的对象,第二层才是实际的文档数组)。 - key值的绑定:每个
v-for都要绑定唯一的:key,这里用循环的索引(index/contractIndex)是简单的方式,如果有唯一ID(比如contract._id),用ID会更优。 - 空数组处理:如果担心某些person没有关联合同,可以给内层循环加上
v-if="person.inner_hits.top_hits.hits.hits.length > 0",避免显示空列表:<ul v-if="person.inner_hits.top_hits.hits.hits.length > 0" style="margin-left: 20px; margin-top: 8px;"> <!-- 合同循环内容 --> </ul> <div v-else>暂无关联合同</div>
这样就能完整解析并展示所有嵌套数组的内容啦!
内容的提问来源于stack exchange,提问作者Roy Granit
相关产品推荐
相关产品推荐

