Abishek R Srikaanth Abishek R Srikaanth - 6 months ago 12
Javascript Question

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?

Answer

A plain JavaScript solution:

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");
Comments