使用来自不同循环Javascript的数据创建数组

时间:2016-05-11 11:52:40

标签: javascript

我这样做,我想分配给一张票,数据:

var recent = [];

for (i = 0; i < data.data.users.length; i++) {
    var userid = data.data.users[i].id;
    recent[userid] = "name":data.data.users[i].name;
}

for (j = 0; j < data.data.tickets.length; j++) {
    var requesterid = data.data.tickets[j].requester_id;
    var created_at = data.data.tickets[j].created_at;
    var tickettitle = data.data.tickets[j].subject;
    var ticketstatus = data.data.tickets[j].status;
    var arrayRef = recent[requesterid] || [];
    recent[requesterid] = arrayRef.concat([{
            "date": created_at,
            "titre": tickettitle,
            "status": ticketstatus,
            "tag": tag,
            "id": requesterid

        }]);
}

一些解释:userid和requesterid是相同的值。

我想添加&#34; name&#34;在我的阵列中但是&#34;名称&#34;在前一个循环中包含,所以它会导致麻烦。 你可以帮我吗?

最后我想要这样的东西:

[
O:{name:"test",date:"mydate",status:"mystatus",tag:"tag",id:"007"}
1:{name:"test2",date:"mydate2",status:"mystatus2",tag:"tag2",id:"0072"}
]

1 个答案:

答案 0 :(得分:0)

这一行没有任何意义(语法也可能是错误的)

recent[userid] = "name":data.data.users[i].name;

如果你想要add "name" in my array

然后

recent[userid] = { "name": data.data.users[i].name }; //now recent is an array of object

或只是

recent[userid] = data.data.users[i].name; 

现在你需要为第二个循环使用与recent不同的数组

var recentArr = [];
for (j = 0; j < data.data.tickets.length; j++) {
    var requesterid = data.data.tickets[j].requester_id;
    var created_at = data.data.tickets[j].created_at;
    var tickettitle = data.data.tickets[j].subject;
    var ticketstatus = data.data.tickets[j].status;
    var arrayRef = recentArr[requesterid] || [];
    recentArr[requesterid] = arrayRef.concat([{
            "date": created_at,
            "titre": tickettitle,
            "status": ticketstatus,
            "tag": tag,
            "id": requesterid
            "name" : recent[requesterid] 
        }]);
}

最后一行可以更改为(避免创建用于连接的数组)

    recentArr[requesterid] = recentArr[requesterid] || [];
    recentArr[requesterid].push ({
            "date": created_at,
            "titre": tickettitle,
            "status": ticketstatus,
            "tag": tag,
            "id": requesterid
            "name" : recent[requesterid] 
        });