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

使用filter筛选jsonplaceholder的comments数据返回空数组如何解决

问题原因

jsonplaceholder的comments接口返回的每条评论数据中,关联所属帖子的字段名为全小写的postId,你代码中使用的postID(末尾D大写)和实际字段名大小写不匹配,全等判断x.postID === 1永远返回false,因此filter筛选结果为空数组。

修复方案

方案1:修正前端筛选字段名

如果需要拉取全量评论后再自行筛选,将判断条件的字段名改为和接口返回一致的postId即可:

axios.get('https://jsonplaceholder.typicode.com/comments').then((result) => {
  // 修正字段名大小写
  console.log(result.data.filter(x => x.postId === 1))
  // lodash的find方法同理修改字段名
  // const arr = _.find(result.data, { postId: 1});
  // console.log(arr);
}).catch((err) => {
 console.log(err);
});

方案2:使用接口自带查询参数(更推荐)

jsonplaceholder的接口原生支持按字段过滤查询,直接在请求url携带postId参数,无需拉取全量数据再前端筛选,性能更高:

axios.get('https://jsonplaceholder.typicode.com/comments?postId=1').then((result) => {
  // 接口直接返回postId为1的所有评论
  console.log(result.data)
}).catch((err) => {
 console.log(err);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 14:06:03