如何使用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
相关产品推荐
相关产品推荐

