javascript 如何使用 jQuery 更新 Json 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13452498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:49:40  来源:igfitidea点击:

How can I update a Json Object using jQuery?

javascriptjqueryjson

提问by Sadda-shutu

Hi all, i am concatenating a JSONstring like this:

大家好,我正在连接这样的JSON字符串:

      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?

如何根据它的 id 更新 json 对象的这个特定值?

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

假设我想更改对象的某些值,其中AddressID=2. 例如,我想更改EmailID,StreetnameJSON对象,其中AddressID=2. 我如何使用 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
        }
    });
}

回答by pala?н

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

您可以arr使用该$.each()函数循环遍历数组,然后搜索id属性值在哪里2。如果找到,则更新对象中所需的属性obj,然后跳出循环,如:

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>

回答by Rune FS

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

如果您需要查找具有给定 ID 的地址,则该方法将取决于您是在addressesAsArray 还是addressesAsObject 中查找。后者是直接的

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 = JSON.stringify(adresses);

回答by Boris Gappov

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

使用 linq.js javascript 库或 jquery 插件: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>