2013-07-05 39 views
1

我剛剛開始使用這個,所以我對如何處理以下內容感到困惑。操縱JSON對象:如何引用和更新嵌套值

// so I believe this really isn't an object just a string representation, but for example please excuse the name 
var dataObj = "{'id': 1, 
       'data': { 'color': 'red', 
          'shape' : 'triangle', 
          'height' : 100, 
          'width' : 45, 
          }, 
       'id': 2, 
       'data': { 'color': 'blue', 
          'shape' : 'square', 
          'height' : 75, 
          'width' : 67, 
          }, 
       'id': 3, 
       'data': { 'color': 'orange', 
          'shape' : 'circle', 
          'height' : 89, 
          'width' :24, 
          } 
       }"; 

等什麼我有一個問題是我怎麼會由ID(如SQL UPDATE WHERE東西的那種)更新的數據值的特定子集? javascript或jquery對我來說真的不重要,只是不知道任何一種方法。

dataObjUpdate(2);  
function dataObjUpdate (passedID) { 

    //access the data by the passedID match and update the color to black 
} 

感激幫助傢伙....

+0

JSON是一種數據序列化格式(在你的問題的字符串你的對象不是的方式有效的JSON,JSON使用雙引號)。您可以刪除引號,並且您將得到一個有效的JavaScript對象 –

+1

數據格式更重要的問題是''id'屬性在序列化對象中多次出現。我想你可能想改變成一個對象數組,而不是這個對象。 – Sirko

+0

是的,這是有道理的....不好的例子失敗:)。謝謝 – Justin

回答

2

如果我們忽略我離開了註釋,假設你有一個JavaScript對象。我看到以下問題:

  • 您的ID位於您的嵌套對象之外。
  • 你正在使用一個對象,但你想要一個'列表'你可以使用一個數組。

這裏是我想構建對象自己:

var data = [{ 
     color : 'red', 
     shape : 'triangle', 
     height : 100, 
     width : 45, 
     id:1 
    }, 
    { 
     color: 'blue', 
     shape : 'square', 
     height : 75, 
     width : 67, 
     id: 2 
    }, 
    { 
     color: 'orange', 
     shape : 'circle', 
     height : 89, 
     width :24, 
     id :3 
    }]; 

現在,我可以查詢它像你期望的使用filter

var id3 = data.filter(function(elem){ 
      return elem.id === 3; 
      })[0]; 
    id3;//the third object, with id 3 

ES6有一個名爲方法find這將在末尾節省[0](這意味着第一個元素)

var id3 = data.find(function(elem){ 
      return elem.id === 3; 
      }); 
    id3;//the third object, with id 3 

或者,你可以使用一個簡單的for循環

var id3 = (function find(arr){ 
       for(var i=0;i<arr.length;i++){ 
        if(arr[i].id === 3){ 
         return arr[i]; 
        } 
       } 
      })(data); 
id3; 
+0

id的字典也使(並且更高性能)。這是如果id是唯一的 – prauchfuss

+0

是的,這是一個有效的點,索引在另一個對象(或地圖)的ID可能是非常有益的。如果您要存儲大量數據並且只支持現代瀏覽器,則還應該考慮IndexedDB。更不用說,如果ID是順序的,你可以通過數組索引訪問元素。 –

+0

謝謝本傑明!我感謝幫助/指導!我不太明白索引的方法,但我想這是另一個問題:)。不勝感激! – Justin