Warm tip: This article is reproduced from stackoverflow.com, please click
javascript jquery json

Updating a JSON object using Javascript

发布于 2020-03-27 10:19:08

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?

Questioner
Abishek
Viewed
92
Michael Berkowski 2019-02-21 00:11

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