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

如何使用if条件修改JSON现有数据并完成打印输出

解决方法

你可以用数组的forEach方法遍历所有元素,同时校验score > 5和当前状态为Unposted两个条件,满足就修改对应字段即可,不会影响原本就是Posted的条目。

完整可运行代码

let data = [
    {
        title: "The Only Guide You Need",
        score:8,
        status: "Posted"
    },
    {
        title: "The Advanced Guide To Archive",
        score:5,
        status: "Unposted"

    },
    {
        title: "In Defense of the Figurative Use of Literally.",
        score:6,
        status: "Unposted",
    },
]

// 核心修改逻辑
data.forEach(item => {
  if (item.score > 5 && item.status === "Unposted") {
    item.status = "Posted"
  }
})

console.log(data)

结果说明

运行后打印的数组中:

  • 第一个条目原本就是Posted,不会修改
  • 第二个条目score等于5,不满足条件,保持Unposted
  • 第三个条目score为6大于5,状态会修改为Posted

完全符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

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