为了账号安全,请及时绑定邮箱和手机立即绑定

替换 JSON 中数组中的键和字符串

替换 JSON 中数组中的键和字符串

LEATH 2023-11-12 15:08:51
我有下面这个 JSON:{    "class": "List",    "list": [{            "name": "HandsUp"            "schedule": {                "type": "probability",                "theme": "Regular",                "occurance": {                    "next": 1607687249008.9834,                    "prev": null                }            }        }, {            "name": "Listing",            "waitingScreenInfo": {                "__class": "WaitingScreenInfo",                "getRecapTime": 1607687753.7949834            },            "schedule": {                "type": "Waiting2",                "theme": "Listing",                "occurance": {                    "next": 1607687249008.9834,                    "prev": null                }            }        }    ]}我有这个:{    "HandsUp": "HandsDown",    "Listing": "ImgList",    "Waiting2": "UpNDown"}第一个 JSON 中的字符串的等效项位于第二个 JSON 中,我想知道如何创建一个函数来查找第一个 JSON 中的字符串的等效项,然后替换所有字符串,即使有多个字符串也是如此?
查看完整描述

1 回答

?
慕森王

TA贡献1777条经验 获得超3个赞

你可以这样做

  • 遍历数组

  • 检查属性名称是否等于“repl”对象中的键

  • 如果是,请使用“repl”对象中的重新分配该值

let stru = {

    "class": "List",

    "list": [{

        "name": "HandsUp",

        "schedule": {

            "type": "probability",

            "theme": "Regular",

            "occurance": {

                "next": 1607687249008.9834,

                "prev": null

            }

        }

    }, {

        "name": "Listing",

        "waitingScreenInfo": {

            "__class": "WaitingScreenInfo",

            "getRecapTime": 1607687753.7949834

        },

        "schedule": {

            "type": "Waiting2",

            "theme": "Listing",

            "occurance": {

                "next": 1607687249008.9834,

                "prev": null

            }

        }

    }]

}


const repl = {

    "HandsUp": "HandsDown",

    "Listing": "ImgList",

    "Waiting2": "UpNDown"

}


console.log("Before ", stru)


stru.list.forEach(element => {

    // keys and values correspond at the index

    let keys = Object.keys(repl);

    let values = Object.values(repl);

    for (let i = 0; i < keys.length; i++) {

        if (keys[i] === element.name) {

            element.name = values[i];

        }

    }


});



console.log("Afterwards ", stru)


查看完整回答
反对 回复 2023-11-12
  • 1 回答
  • 0 关注
  • 53 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信