我会尝试简化我的案例:
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 :(得分: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"}]