亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

替換 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 關注
  • 145 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號