You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nuxt 3与Nuxt Content中查询JSON数组的单个元素?

解决Nuxt 3 + Nuxt Content 2.3.0查询JSON数组单个元素的问题

你的核心问题是:JSON文件本身是数组结构,查询后整个数组被包裹在返回数据的body字段中,直接用.where({ id })无法匹配数组内部的元素属性。以下是两种可行的解决方式:

方式一:先获取完整数据,前端筛选

适合数据量不大的场景,逻辑简单直接:

<template>
  <pre>{{ person }}</pre>
</template>

<script setup>
const route = useRoute();
const targetId = parseInt(route.params.id); // 路由参数是字符串,需转成数字匹配JSON中的id

// 获取完整的people数据文档
const peopleDoc = await queryContent("people").findOne();
// 从body数组中筛选对应id的元素
const person = peopleDoc.body.find(item => item.id === targetId);
</script>

方式二:结合Nuxt Content的数组字段匹配语法

利用Nuxt Content 2.x支持的嵌套字段匹配,先筛选出包含目标元素的文档,再提取具体元素:

<template>
  <pre>{{ matchedPerson }}</pre>
</template>

<script setup>
const route = useRoute();
const targetId = parseInt(route.params.id);

// 通过body.id匹配数组内的元素,返回包含该元素的文档
const peopleDoc = await queryContent("people")
  .where({ "body.id": targetId })
  .findOne();

// 从文档的body数组中提取目标元素
const matchedPerson = peopleDoc.body.find(item => item.id === targetId);
</script>

关键注意事项

  • 路由参数route.params.id默认是字符串类型,而你的JSON中id是数字,必须用parseInt转换类型,否则匹配会失败。
  • 第二种方式中,Nuxt Content的.where只会返回包含符合条件元素的整个文档,无法直接返回单个数组元素,因此仍需二次筛选。

内容的提问来源于stack exchange,提问作者duffn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 23:55:32