2015-09-25 71 views
0

我會盡量簡化我的情況:

offenses = {}; 

$(offenseTableID).find('tr').each(function (rowIndex, r) { 
    // building JSON object named "offense" with object with 
    // information from the table row. 
    // console.log shows It's correct. I typically have 3 rows 
    // showing different information. 

// I am trying to extend offenses with what I constructed.      
$.extend(offenses, offense); 

}); 

// after I'm done I'm printing my "offenses" JSON object, 
// expecting it to include everything that was added, but even if 
// I $.extend multiple times - it only remembers the last JSON 
// object that was $.extend'ed Why? 

console.log(JSON.stringify(offenses)); 
+0

$ .extend與其他PARAMS和覆蓋第一個參數最後的值贏得 – Saar

+0

任何理由不在數組中存儲攻擊,只使用array.push? – Saar

+0

所以沒有追加JSON對象? – JasonGenX

回答

1

這是因爲對象必須具有唯一鍵。你不能簡單地追加一個新的對象到現有的對象,並期望它是有用的。你真正想要的是數組的對象。

offenses = []; 

$(offenseTableID).find('tr').each(function (rowIndex, r) { 
    // building object named "offense" with object with 
    // information from the table row. 
    // console.log shows It's correct. I typically have 3 rows 
    // showing different information. 

    // I am trying to extend offenses with what I constructed.      
    offenses.push(offense); 

}); 

這將導致一個數組,看起來像這樣:

[{name:'bob'},{name:'frank'}] 

可以再這個字符串化到JSON:

[{"name":"bob"},{"name":"frank"}] 
相關問題