javascript - 如何修改现有数据,使用带有 JSON 的 if 条件
问题描述
我是一个刚学习 JSON 的新手程序员,想问一个问题如何更改数据并打印它
基于条件如果分数 > 5,状态从未发布更改为已发布
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",
},
]
console.log(data)
**先感谢您
解决方案
只需使用Array.prototype.map循环遍历每个元素。如果分数大于 5,则设置status
为"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 = data.map((current) => {
if (current.score > 5) current.status = "Posted";
return current;
});
console.log(data)
推荐阅读
- python - 以视觉/图形方式表示 Graph 数据结构
- c# - 无法在简单查询中翻译 LINQ 表达式
- ruby-on-rails - RAILS 5:ActionController::ParameterMissing - 无法让 RSPEC 通过
- javascript - jQuery 3D透视图
- css - 你能帮我理解这段css代码会做什么吗?
- php - 将不带表单的模态引导详细信息保存到 sql
- rspec - 如何为 link_to 辅助方法编写 RSpec 测试?
- python - Pandas:按特定行获取百分位数
- reactjs - React Native View 和 Flex: 1 没有按预期工作
- julia - 沿维度扩展数组