2016-03-15 23 views
0

這是JSON replacement 的後續問題,我無法獲得正確的響應。因此,我用一個更好的例子發佈這個問題。使用javascript更新後替換JSON對象

var beforeReplacement=[ 
    { 
     "Name": "app1", 
     "id": "1", 
     "groups": [ 
      { 
       "id": "test1", 
       "name": "test grp45", 
       "desc": "this is a test group" 
      }, 
      { 
       "id": "test2", 
       "name": "test group 2", 
       "desc": "this is another test group" 
      } 
     ] 
    }, 
    { 
     "Name": "app2", 
     "id": "2", 
     "groups": [ 
      { 
       "id": "test3", 
       "name": "test group 4", 
       "desc": "this is a test group" 
      }, 
      { 
       "id": "test4", 
       "name": "test group 4", 
       "desc": "this is another test group" 
      } 
     ] 
    } 
] 


changed object: 
[ 
     { 
      "Name": "app2", 
      "id": "2", 
      "groups": [ 
       { 
        "id": "test3", 
        "name": "changed test group 4", 
        "desc": "this is a test group" 
       } 

      ] 
     } 
    ] 





var afterReplacement=[ 
     { 
      "Name": "app1", 
      "id": "1", 
      "groups": [ 
       { 
        "id": "test1", 
        "name": "test grp45", 
        "desc": "this is a test group" 
       }, 
       { 
        "id": "test2", 
        "name": "test group 2", 
        "desc": "this is another test group" 
       } 
      ] 
     }, 
     { 
      "Name": "app2", 
      "id": "2", 
      "groups": [ 
       { 
        "id": "test3", 
        "name": "changed test group 4", 
        "desc": "this is a test group" 
       }, 
       { 
        "id": "test4", 
        "name": "test group 4", 
        "desc": "this is another test group" 
       } 
      ] 
     } 
    ] 

我在變種beforeReplacement更名並已提到,我將在改變之後接收到經修改的對象。我怎樣纔能有效地替換此更改的對象在beforeReplacement從而使得到的對象會像變種afterReplacement

+0

如果要更改測試的ID,你怎麼能涉及到哪些測試你有改變了嗎? – gurvinder372

+0

@ gurvinder372更新了ID,謝謝 – forgottofly

+0

問題沒有指定更改的對象來自哪裏,並且不夠具體。你可能想要(特別是如果你有服務器端的JS)使用一些JSON比較庫(例如[node-rus-diff](https://github.com/mirek/node-rus-diff))來計算並將diff應用於現有對象。許多NPM庫是平臺不可知的,可以使用Browserify或Webpack爲瀏覽器構建。 – estus

回答

1
var afterReplacement = beforeReplacement.map(function (af) { 
    for(var i in changed) { 
     if (changed[i].id != af.id) continue; 

     af = changed[i]; 
     break; 
    } 
    return af; 
}); 
+0

forEach對於大型數組將會效率很低。 – Tibrogargan

+0

你有同樣的問題。將其改爲{af = ch;打破; } – Tibrogargan

+0

轉換爲for-in :) – kazupooot