Sadda-shutu
Sadda-shutu

Reputation: 1309

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":[email protected],
   "Hno":Hyderabad,
   "StreetName":Gachibowli,
   "City":Hyderabad,
   "StateID":1,
   "CountryID":1,
   "Zip":040,
   "PhoneNumber":8341516166,
   "Fax":23123131,
   "AddressName:Store Address"},
 { 
   "AddressID":3,
   "EmailID":[email protected],
   "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
        }
    });
}

Upvotes: 1

Views: 14948

Answers (3)

palaѕн
palaѕн

Reputation: 73906

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>

Upvotes: 3

Boris Gappov
Boris Gappov

Reputation: 2493

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:'[email protected]',
       Hno:'Hyderabad'
       },
     { 
       AddressID:3,
       EmailID:'[email protected]',
       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>

Upvotes: -1

Rune FS
Rune FS

Reputation: 21742

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

Upvotes: 0

Related Questions