简体   繁体   中英

How can I update a Json Object using jQuery?

Hi all, i am concatenating a JSON string like this:

      var addresses = "[";

         addresses += '{"AddressID":' + adressid + ',"EmailID":' + $('#txtemailData').val() + ',"Hno":' + $('#txthno').val() + ',"StreetName":' + $('#txtstreetname').val() + ',"City":' + $('#txtcity').val() + ',"StateID":' + $('#ddlState').val() + ',"CountryID":' + $('#ddlcountry').val() + ',"Zip":' + $('#txtzip').val() + ',"PhoneNumber":' + $('#txtphonenumber').val() + ',"Fax":' + $('#txtfax').val() + ',"AddressName:' + $('#txtaddresstype').val() + '"},';

And the object looks like this:

[{
   "AddressID":2,
   "EmailID":akanilkumar443@gmail.com,
   "Hno":Hyderabad,
   "StreetName":Gachibowli,
   "City":Hyderabad,
   "StateID":1,
   "CountryID":1,
   "Zip":040,
   "PhoneNumber":8341516166,
   "Fax":23123131,
   "AddressName:Store Address"},
 { 
   "AddressID":3,
   "EmailID":akanilkumar443@gmail.com,
   "Hno":aSAs,
   "StreetName":asdasdad,
   "City":asdasda,
   "StateID":1,
   "CountryID":1,
   "Zip":asdasda,
   "PhoneNumber":asdasda,
   "Fax":asdasda,
"AddressName:Store Type"
}]

How can I update this particular value of json object based on it's id?

Suppose I want to change some of the values of my object where AddressID=2 . For example, I want to change the EmailID , Streetname of JSON objects where AddressID=2 . How can I do this using jQuery?

I am trying it like this, but it's not going in the loop, Can any one help me here please?

    function EditAddress(addressid) {
    alert(addressid);
    alert(addresses);
    var addressobject =JSON.parse(addresses.substring(0, addresses.length - 1) + ']');
    jQuery.each(addressobject, function (i, val) {
        alert(val.AddressID);
        if (val.AddressID == addressid) 
        {
            //update logic
        }
    });
}

You can just loop through the array arr using the $.each() function, then search for where id property value is 2 . If found then update the required property in the object obj and then break out of the loop like:

 var arr = [ {"id": 1, "name": "Apple" , "isVisible": false}, {"id": 2, "name": "Orange", "isVisible": false}, {"id": 3, "name": "Banana", "isVisible": false} ] $.each( arr, function( i, obj ) { if(obj.id === 2){ console.log("Current " + obj.id + " = " + obj.isVisible); obj.isVisible = true; console.log("Changed " + obj.id + " = " + obj.isVisible); return false; // Loop will stop running after this } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script>

Firstly don't create the string by hand. It's a lot more robust to use build-in features so do this:

var addressesAsArray = [],
    addressAsObject = {}
    address;
//assuming some loop or other
address = {
              "AddressID": adressid,
              "EmailID":$('#txtemailData').val(),
              "Hno":$('#txthno').val(),
              "StreetName": $('#txtstreetname').val(),
              "City": $('#txtcity').val(),
              "StateID": $('#ddlState').val(),
              "CountryID": $('#ddlcountry').val(),
              "Zip": $('#txtzip').val(),
              "PhoneNumber": $('#txtphonenumber').val(),
              "Fax": $('#txtfax').val(),
              "AddressName": $('#txtaddresstype').val()
          };
addressesAsArray.push(address);
addressAsObject[address.AddressID] = address;    

if you need to find an address with a given ID the approach would depend on whether you are looking in addressesAsArray or in addressesAsObject. The latter is straight forward

address = addressesAsObject[addressIDBeingSought];

in the array case you can simply loop

for(i = 0, len = addressesAsArray.length;i<len; i += 1){
   if(addressesAsArray[i].AddressID === addressIDBeingSought) {
       address = addressesAsArray[i];
       break;
   }
}

when you are done with the updating you can then get that as JSON by

json = JSON.stringify(adresses);

use linq.js javascript library or jquery plugin: http://linqjs.codeplex.com/

    <!DOCTYPE>
    <html>
    <head>
        <script type="text/javascript" src="linq.js"></script>
    </head>
    <body>
    <script>  
    var array = [{
       AddressID:2,
       EmailID:'akanilkumar443@gmail.com',
       Hno:'Hyderabad'
       },
     { 
       AddressID:3,
       EmailID:'akanilkumar443@gmail.com',
       Hno:'aSAs'
    }];
    Enumerable.From(array).Where("$.AddressID == 3").ToArray()[0].Hno= 'ololo'; 
// or this: 
// Enumerable.From(array).Where(function(x){return x.AddressID == 3}).ToArray()[0].Hno= 'ololo'; 
    alert(array[1].Hno)  
    </script>
    </body>
    </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM