Abishek R Srikaanth Abishek R Srikaanth - 1 year ago 49
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'},

I would like to dynamically update the Username to 'Thomas' where the 'Id' is '3'.

How can I acheive this?

Answer Source

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

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;

// Call as
setUsername(3, "Thomas");