首页 > 解决方案 > 如何修改现有数据,使用带有 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)

**先感谢您

标签: javascriptjson

解决方案


只需使用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)


推荐阅读