1

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
        }
    });
}
5
  • 3
    Why built a JSON string manually, if you want to use the object? Commented Nov 19, 2012 at 11:08
  • 1
    Did I just notice a ninja spammer around here? Commented Nov 19, 2012 at 11:11
  • The JSON you are creating is not valid JSON. No JSON parser will be able to parse that, let alone modify. Commented Nov 19, 2012 at 11:13
  • I'm not certain what context this code is in... but if you are trying to manipulate JSON data and it's a frequent occurrence, might I suggest using a client side MVC framework like backbonejs.org ? Commented Nov 19, 2012 at 11:18
  • do you need an array? or could another collection fit the purpose? Commented Nov 19, 2012 at 11:18

3 Answers 3

3

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

-1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.