Updating a JSON object using Javascript

前端 未结 9 1532
Happy的楠姐
Happy的楠姐 2020-12-07 13:37

How can i update the following JSON object dynamically using javascript or Jquery?

var jsonObj = [{\'Id\':\'1\',\'Username\':\'Ray\',\'FatherName\':\'Thompso         


        
相关标签:
9条回答
  • 2020-12-07 13:57

    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);
        }    
      });
    
    }
    
    0 讨论(0)
  • 2020-12-07 13:58
        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);
      }
    
    0 讨论(0)
  • 2020-12-07 14:02

    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';
        }
    }
    
    0 讨论(0)
  • 2020-12-07 14:08

    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.

    0 讨论(0)
  • 2020-12-07 14:13
    $(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);
    
    });
    
    0 讨论(0)
  • 2020-12-07 14:14
    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';
    
    0 讨论(0)
提交回复
热议问题