【问题标题】:Updating a JSON object using Javascript使用 Javascript 更新 JSON 对象
【发布时间】:2012-01-31 21:57:05
【问题描述】:

如何使用 javascript 或 Jquery 动态更新以下 JSON 对象?

var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},  
               {'Id':'2','Username':'Steve','FatherName':'Johnson'},
               {'Id':'3','Username':'Albert','FatherName':'Einstein'}]

我想将用户名动态更新为“Thomas”,其中“Id”为“3”。

我怎样才能做到这一点?

【问题讨论】:

  • JSON 代表 JavaScript 对象表示法。这是js理解得很简单的东西。您的问题不涉及 JSON。它纯粹处理 js 对象操作。 “使用 Javascript 更新 JSON 对象”是一个没有实际意义的表达,因为它转换为“使用 Javascript 更新 Javascript 对象”。
  • Zirak ,派对一定很有趣

标签: javascript jquery json


【解决方案1】:

一个普通的 JavaScript 解决方案,假设 jsonObj 已经包含 JSON:

循环查找匹配的Id,设置对应的用户名,修改匹配项后循环break

for (var i = 0; i < jsonObj.length; i++) {
  if (jsonObj[i].Id === 3) {
    jsonObj[i].Username = "Thomas";
    break;
  }
}

Here it is on jsFiddle.

这是同样的东西包裹在一个函数中:

function setUsername(id, newUsername) {
  for (var i = 0; i < jsonObj.length; i++) {
    if (jsonObj[i].Id === id) {
      jsonObj[i].Username = newUsername;
      return;
    }
  }
}

// Call as
setUsername(3, "Thomas");

【讨论】:

  • 上述解决方案适用于提琴手。我有问题中的 json 字符串,为了使其在 ASP.NET MVC 5 Razor 视图中工作,我必须使用 obj = JSON.parse(jsonObj); 将字符串解析为 json;在操纵之前。希望它可以帮助某人。顺便说一句,我投了赞成票,因为该解决方案有效。
  • 这是一个很好的解决方案。我在下面的回答中更进一步。
【解决方案2】:

只需遍历列表,然后检查每个对象的属性。

for (var i = 0; i < jsonObj.length; ++i) {
    if (jsonObj[i]['Id'] === '3') {
        jsonObj[i]['Username'] = 'Thomas';
    }
}

【讨论】:

    【解决方案3】:
    $(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);
    
    });
    

    【讨论】:

    • 对于想知道的人来说,jQuery 的 $.each() 似乎是 way slower 而不是普通的 for 循环。
    【解决方案4】:

    使用:

    var parsedobj = jQuery.parseJSON( jsonObj);
    

    这仅在您不需要将格式保留在字符串中时才有用。 否则您必须使用 JSON 库将其转换回 JSON。

    【讨论】:

      【解决方案5】:
      var i = jsonObj.length;
      while ( i --> 0 ) {
          if ( jsonObj[i].Id === 3 ) {
              jsonObj[ i ].Username = 'Thomas';
              break;
          }
      }
      

      或者,如果数组总是按 ID 排序:

      jsonObj[ 2 ].Username = 'Thomas';
      

      【讨论】:

        【解决方案6】:

        JSON 是 JavaScript 对象表示法。没有像 JSON 对象 这样的东西。 JSON 只是一种在文本中表示 JavaScript 对象的方式。

        因此,您所追求的是一种更新内存中 JavaScript 对象的方法。 qiao's answer 展示了如何简单地做到这一点。

        【讨论】:

          【解决方案7】:

          我将Michael Berkowski 的回答更进一步(或两步),并创建了一个更灵活的函数,允许任何查找字段和任何目标字段。为了好玩,我在那里扔了 splat (*) 功能,以防有人可能想要全部替换。 不需要 jQuery。 checkAllRows 允许选项从找到的搜索中中断以提高性能或前面提到的全部替换。

          function setVal(update) {
              /* Included to show an option if you care to use jQuery  
              var defaults = { jsonRS: null, lookupField: null, lookupKey: null,
                  targetField: null, targetData: null, checkAllRows: false }; 
              //update = $.extend({}, defaults, update); */
          
              for (var i = 0; i < update.jsonRS.length; i++) {
                  if (update.jsonRS[i][update.lookupField] === update.lookupKey || update.lookupKey === '*') {
                      update.jsonRS[i][update.targetField] = update.targetData;
                      if (!update.checkAllRows) { return; }
                  }
              }
          }
          
          
          var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},  
                     {'Id':'2','Username':'Steve','FatherName':'Johnson'},
                     {'Id':'3','Username':'Albert','FatherName':'Einstein'}]
          

          使用您的数据,您将使用:

          var update = {
              jsonRS: jsonObj,
              lookupField: "Id",
              lookupKey: 2, 
              targetField: "Username",
              targetData: "Thomas", 
              checkAllRows: false
              };
          
          setVal(update);
          

          鲍勃是你的叔叔。 :) [效果很好]

          【讨论】:

            【解决方案8】:

            例如,我在篮子功能中使用了这种技术。

            让我们将新项目添加到购物篮。

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

            将一些项目添加到购物篮后 - 生成这样的 json 数组

            [
                {
                    "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"
                }
            ]
            

            用于从篮子中移除一些物品。

            $(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);
            
                }    
              });
            }
            

            最后是“使用 JS 更新 JSON 对象”问题的真正答案。在我的示例中,通过更改“数字”元素值来更新产品数量和总价。

            $(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);
                }    
              });
            
            }
            

            【讨论】:

              【解决方案9】:

              我认为这比 for 循环更有效。

              1-首先找到项目的索引。 2-秒编辑精确元素。 (如果不存在添加)

              例子:

              let index= jsonObj.findIndex(x => x["Id"] === 3); 
              if (index == -1) {
               // add
               jsonObj.push({ id:3, .... });
               } else {
                // update
                 jsonObj[index]["Username"]="xoxo_gossip_girl"
               }
              

              【讨论】:

              • “更新”部分中不是缺少索引来指定要修改哪一行吗?例如jsonObj[index]["用户名"]="xoxo_gossip_girl"
              • 是的,你是对的,我编辑了那行。
              【解决方案10】:
                  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);
                }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2012-09-23
                • 1970-01-01
                • 2019-08-26
                • 2013-05-15
                • 2017-10-21
                • 1970-01-01
                相关资源
                最近更新 更多