如何使用json对象的一个字段来查找不同json对象中的另一个字段?(Javascript)



基本上,我有一个Get请求,它向我返回一个带有多个json对象的响应。我需要根据他的名字获得一个特定的json对象,处理这个名字,并根据修改后的名字找到另一个对象的id(在javascript中(
示例:

  • 我有一个json,名称为:"XXXX出版";,id:";1〃
  • 我需要得到这个名字,把它改成";XXXX受限";并查找具有该名称的对象的id

有人能给我一个代码片段吗

我假设了这个响应中的响应格式,如果它不正确,请告诉我。

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)

最新更新