基本上我有一個 Get 請求,它回傳一個包含多個 json 物件的回應。我需要根據他的名字獲取一個特定的 json 物件,操作該名稱并根據修改后的名稱(在 javascript 中)找到另一個物件的 id。
例子:
- 我有一個 json 名稱:“XXXX Published”,id:“1”。
- 我需要獲取名稱,將其更改為“XXXX Restricted”并找到具有該名稱的物件的 ID。
任何人都可以給我一個代碼片段來幫助我作業嗎?
uj5u.com熱心網友回復:
我已經假設了此回應中的回應格式,如果它不正確,請告訴我。
const response = [
{id: 1, name: "XXXX Published"},
{id: 2, name: "XXXX Restricted"},
{id: 3, name: "h3"}
]
function replaceName(findName, name) {
const index = response.findIndex(i => i.name === findName)
if(index !== -1) {
response[index].name = name;
}
}
const oldName = "XXXX Published";
const newName = 'XXXX Restricted'
// This is the id that already has the new name
const originalId = response.find(i => i.name === newName)?.id;
// This mutates the response and changes the name
replaceName(oldName, newName)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/403340.html
標籤:
