JSON (JavaScript Object Notation) is now an everyday term that a developer uses to represent data, whether it be client side, server side and now a days on the database as well. Most server side technologies have a in built functions to convert a json object into an array or dictionary to manipulate data. When I started looking at how I do the same with Javascript/jQuery, there wasn't an in-built function to do this. Below is a solution that can help you achieve this.

Example Data

var jsonObj = [{'id':1,'first_name':'Ray','last_name':'Thompson'},  
               {'id':2,'first_name':'Steve','last_name':'Johnson'},
               {'id':3,'first_name':'Albert','last_name':'Einstein'}]

What I would like to do is to dynamically update the first_name to 'Thomas' where the id is 3.


A plain JavaScript solution (Before ES6):

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].first_name = "Thomas";
    break;
  }
}

Here's the same thing wrapped in a function:

function setFirstName(id, newFirstName) {
  for (var i = 0; i < jsonObj.length; i++) {
    if (jsonObj[i].id === id) {
      jsonObj[i].first_name = newFirstName;
      return;
    }
  }
}

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

ES6 Approach

ES6 offers the forEach method that helps simplify this substantially.

let newFirstName = 'Thomas';
jsonObj.forEach((item) => {
   if(item.id === 3) {
       item.first_name = newFirstName;
   }
});

jQuery:

$(document).ready(function(){        
    var jsonObj = [{'id':1,'first_name':'Ray','last_name':'Thompson'},  
               {'id':2,'first_name':'Steve','last_name':'Johnson'},
               {'id':3,'first_name':'Albert','last_name':'Einstein'}];

    $.each(jsonObj,function(i,v){       
      if (v.Id == 3) {
        v.first_name = "Thomas";
        return false;
      }
    });

    alert("New First Name is : " + jsonObj[2].first_name);
});