2015-09-25 70 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"}] 
相关问题