Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a JSON object using Javascript

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?

like image 541
Abishek Avatar asked Jan 02 '12 15:01

Abishek


People also ask

How do I change the value of a JSON object?

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.

Can we update JSON?

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.

Can JavaScript write to a JSON file?

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.


2 Answers

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"); 
like image 130
Michael Berkowski Avatar answered Oct 10 '22 13:10

Michael Berkowski


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';     } } 
like image 42
qiao Avatar answered Oct 10 '22 13:10

qiao