How can i update the following JSON object dynamically using javascript or Jquery?
var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},
{'Id':'2','Username':'Steve','FatherName':'Johnson'},
{'Id':'3','Username':'Albert','FatherName':'Einstein'}]
I would like to dynamically update the Username to 'Thomas' where the 'Id' is '3'.
How can I acheive this?
A plain JavaScript solution, assuming jsonObj
already contains JSON:
Loop over it looking for the matching Id, set the corresponding Username, and break
from the loop after the matched item has been modified:
for (var i = 0; i < jsonObj.length; i++) {
if (jsonObj[i].Id === 3) {
jsonObj[i].Username = "Thomas";
break;
}
}
Here's the same thing wrapped in a function:
function setUsername(id, newUsername) {
for (var i = 0; i < jsonObj.length; i++) {
if (jsonObj[i].Id === id) {
jsonObj[i].Username = newUsername;
return;
}
}
}
// Call as
setUsername(3, "Thomas");
Above solution works in the fiddler. I had json string as in the question, to make it work in ASP.NET MVC 5 Razor view, I had to parse the string to json using obj = JSON.parse(jsonObj); before manipulating. Hope it helps someone. Btw I upvoted because the solution works.
This is a great solution. I took it a bit farther in my answer below.