我想在我的数组中添加一个索引:
这是我的循环
for(j=0; j< data.data.tickets.length; j++) {
var created_at = data.data.tickets[j].created_at;
var tickettitle = data.data.tickets[j].subject;
cleartab[requesterid]['tickets'] = [{"created":created_at, "titre":tickettitle}];
}
问题是tickets[]
中的密钥总是重写,所以它不是迭代的。因为我的用户有很多票,所以每个索引都是票,每张票都有日期和标题。
答案 0 :(得分:3)
问题是你在for循环的每次迭代中都覆盖了tickets
数组。试试这个
for(j=0; j< data.data.tickets.length ;j++){
var created_at = data.data.tickets[j].created_at;
var tickettitle = data.data.tickets[j].subject;
// Making sure that 'tickets' will be an array
var arrayRef = cleartab[requesterid]['tickets'] || [];
cleartab[requesterid]['tickets'] = arrayRef.concat([{"created":created_at,"titre":tickettitle}]);
}
答案 1 :(得分:0)
这对你有用..
<script>
var cleartab ={tickets :[]};
$.each(data.data.tickets, function(key,val) {
var created_at = val.created_at;
var tickettitle = val.subject;
cleartab.tickets.push({"created":created_at, "title":tickettitle});
});
console.log(cleartab)
</script>