Basically i have a Get request that returns me a response with multiple json objects. I need to get a specific json object based on his name, manipulate that name and find the id of another object based on that modified name (in javascript).
Example:
- I have a json with name: " XXXX Published", id: "1".
- I need to get the name, change it to "XXXX Restricted" and find what is the id of the object with that name.
Can anyone give me a code snippet from which to work my way up?
CodePudding user response:
I've assumed the response format in this response, let me know if it's not correct.
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)
