[javascript] 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?

This question is related to javascript jquery json

The answer is


For example I am using this technique in Basket functionality.

Let us add new Item to Basket.

var productArray=[];


$(document).on('click','[cartBtn]',function(e){
  e.preventDefault();
  $(this).html('<i class="fa fa-check"></i>Added to cart');
  console.log('Item added ');
  var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image'), "quantity":1, "discount":0, "total":$(this).attr('pr_price')};


  if(localStorage.getObj('product')!==null){
    productArray=localStorage.getObj('product');
    productArray.push(productJSON);  
    localStorage.setObj('product', productArray);  
  }
  else{
    productArray.push(productJSON);  
    localStorage.setObj('product', productArray);  
  }


  itemCountInCart(productArray.length);

});

After adding some item to basket - generates json array like this

[
    {
        "id": "95",
        "nameEn": "New Braslet",
        "price": "8776",
        "image": "1462012394815.jpeg",
        "quantity": 1,
        "discount": 0,
        "total": "8776"
    },
    {
        "id": "96",
        "nameEn": "new braslet",
        "price": "76",
        "image": "1462012431497.jpeg",
        "quantity": 1,
        "discount": 0,
        "total": "76"
    },
    {
        "id": "97",
        "nameEn": "khjk",
        "price": "87",
        "image": "1462012483421.jpeg",
        "quantity": 1,
        "discount": 0,
        "total": "87"
    }
]

For Removing some item from Basket.

$(document).on('click','[itemRemoveBtn]',function(){

var arrayFromLocal=localStorage.getObj('product');
findAndRemove(arrayFromLocal,"id",$(this).attr('basketproductid'));
localStorage.setObj('product', arrayFromLocal);
loadBasketFromLocalStorageAndRender();
});

//This function will remove element by specified property. In my case this is ID.
function findAndRemove(array, property, value) {
  array.forEach(function(result, index) {
    if(result[property] === value) {
      //Remove from array
      console.log('Removed from index is '+index+' result is '+JSON.stringify(result));
      array.splice(index, 1);

    }    
  });
}

And Finally the real answer of the question "Updating a JSON object using JS". In my example updating product quantity and total price on changing the "number" element value.

$(document).on('keyup mouseup','input[type=number]',function(){

  var arrayFromLocal=localStorage.getObj('product');
  setQuantityAndTotalPrice(arrayFromLocal,$(this).attr('updateItemid'),$(this).val());
  localStorage.setObj('product', arrayFromLocal);
  loadBasketFromLocalStorageAndRender();
});

function setQuantityAndTotalPrice(array,id,quantity) {

  array.forEach(function(result, index) {
    if(result.id === id) {
      result.quantity=quantity;
      result.total=(quantity*result.price);
    }    
  });

}

I took Michael Berkowski's answer a step (or two) farther and created a more flexible function allowing any lookup field and any target field. For fun I threw splat (*) capability in there incase someone might want to do a replace all. jQuery is NOT needed. checkAllRows allows the option to break from the search on found for performance or the previously mentioned replace all.

function setVal(update) {
    /* Included to show an option if you care to use jQuery  
    var defaults = { jsonRS: null, lookupField: null, lookupKey: null,
        targetField: null, targetData: null, checkAllRows: false }; 
    //update = $.extend({}, defaults, update); */

    for (var i = 0; i < update.jsonRS.length; i++) {
        if (update.jsonRS[i][update.lookupField] === update.lookupKey || update.lookupKey === '*') {
            update.jsonRS[i][update.targetField] = update.targetData;
            if (!update.checkAllRows) { return; }
        }
    }
}


var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},  
           {'Id':'2','Username':'Steve','FatherName':'Johnson'},
           {'Id':'3','Username':'Albert','FatherName':'Einstein'}]

With your data you would use like:

var update = {
    jsonRS: jsonObj,
    lookupField: "Id",
    lookupKey: 2, 
    targetField: "Username",
    targetData: "Thomas", 
    checkAllRows: false
    };

setVal(update);

And Bob's your Uncle. :) [Works great]


    var jsonObj = [{'Id':'1','Quantity':'2','Done':'0','state':'todo',
        'product_id':[315,"[LBI-W-SL-3-AG-TA004-C650-36] LAURA BONELLI-WOMEN'S-SANDAL"],
        'Username':'Ray','FatherName':'Thompson'},  
          {'Id':'2','Quantity':'2','Done':'0','state':'todo',
          'product_id':[314,"[LBI-W-SL-3-AG-TA004-C650-36] LAURA BONELLI-WOMEN'S-SANDAL"],
          'Username':'Steve','FatherName':'Johnson'},
          {'Id':'3','Quantity':'2','Done':'0','state':'todo',
          'product_id':[316,"[LBI-W-SL-3-AG-TA004-C650-36] LAURA BONELLI-WOMEN'S-SANDAL"],
          'Username':'Albert','FatherName':'Einstein'}];

          for (var i = 0; i < jsonObj.length; ++i) {
            if (jsonObj[i]['product_id'][0] === 314) {


                this.onemorecartonsamenumber();


                jsonObj[i]['Done'] = ""+this.quantity_done+"";

                if(jsonObj[i]['Quantity'] === jsonObj[i]['Done']){
                  console.log('both are equal');
                  jsonObj[i]['state'] = 'packed';
                }else{
                  console.log('not equal');
                  jsonObj[i]['state'] = 'todo';
                }

                console.log('quantiy',jsonObj[i]['Quantity']);
                console.log('done',jsonObj[i]['Done']);


            }
        }

        console.log('final',jsonObj);
}

quantity_done: any = 0;

  onemorecartonsamenumber() {
    this.quantity_done += 1;
    console.log(this.quantity_done + 1);
  }

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

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

alert("New Username: " + jsonObj[2].Username);

});

var i = jsonObj.length;
while ( i --> 0 ) {
    if ( jsonObj[i].Id === 3 ) {
        jsonObj[ i ].Username = 'Thomas';
        break;
    }
}

Or, if the array is always ordered by the IDs:

jsonObj[ 2 ].Username = 'Thomas';

use:

var parsedobj = jQuery.parseJSON( jsonObj);

This will only be useful if you don't need the format to stay in string. otherwise you'd have to convert this back to JSON using the JSON library.


JSON is the JavaScript Object Notation. There is no such thing as a JSON object. JSON is just a way of representing a JavaScript object in text.

So what you're after is a way of updating a in in-memory JavaScript object. qiao's answer shows how to do that simply enough.


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';
    }
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?