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?
Array value of a JSON object can be modified. It can be simply done by modifying the value present at a given index. Note: If value is modified at an index which is out of the array size, then the new modification will not replace anything in the original information but rather will be an add-on.
You can use Oracle SQL function json_mergepatch to update specific portions of a JSON document. You pass it a JSON Merge Patch document, which specifies the changes to make to a specified JSON document.
If we want to write something in a JSON file using JavaScript, we will first need to convert that data into a JSON string by using the JSON. stringify method. Above, a client object with our data has been created which is then turned into a string. This is how we can write a JSON file using the fileSystem.
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 it is on jsFiddle.
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");
simply iterate over the list then check the properties of each object.
for (var i = 0; i < jsonObj.length; ++i) { if (jsonObj[i]['Id'] === '3') { jsonObj[i]['Username'] = 'Thomas'; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With