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

如何用JavaScript筛选JSON中state为2的用户帖子?

筛选用户state为2的帖子实现方案

嘿,这个需求超简单的!要筛选出John所有state为2的帖子,用JavaScript里的filter()方法就能一步到位,给你看看具体实现:

首先先修正一下你提供的用户数据(原始数据里对象键名没加引号,不符合标准JSON语法,补上后才能正常运行):

const user = { 
  "name": "John", 
  "posts": [ 
    { "id": 1, "state": 1, "title": "Hello" }, 
    { "id": 2, "state": 1, "title": "Hi" }, 
    { "id": 3, "state": 2, "title": "World" }, 
    { "id": 4, "state": 3, "title": "Hey" }, 
    { "id": 5, "state": 2, "title": "Goodbye" } 
  ] 
};

接下来用filter()方法筛选目标帖子:

// 遍历posts数组,只保留state等于2的帖子
const result = user.posts.filter(post => post.state === 2);

运行后result就是你想要的结果:

[ 
  { "id": 3, "state": 2, "title": "World" }, 
  { "id": 5, "state": 2, "title": "Goodbye" } 
]

简单解释下:filter()会创建一个新数组,包含所有通过测试(这里就是post.state === 2)的元素,完全符合你的需求,而且代码简洁易读,性能也不错~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:26:25