我正在尝试将对象推入对象数组。我编写的代码对数组中的所有索引重复最后一个索引值。任何有关我可能做错了事的帮助都将很棒。
代码:
var comment = {
Comment_ID : "",
Text_Displayed : ""
};
var comments = [];
var total = 4;
var i;
for(i = 0 ; i < total ; i++){
comment.Comment_ID = json1.items[i].snippet.topLevelComment.id ;
comment.Text_Displayed = json1.items[i].snippet.topLevelComment.snippet.textDisplay ;
comments.push(comment);
}
json1是原始JSON响应。 我尝试使用JSON.parse(json1)解析它,然后将其转换为Javascript对象,但是这样做,我的数组仍然为空。
json1:
{
"kind": "youtube#commentThreadListResponse",
"etag": "DdP0Qpu15x6rNWi8DqdtP8XHFWk",
"nextPageToken": "QURTSl9pMHRqeTI4QzlFdG9mdE44MFloNlhrS1hJS3FLSFgwS2FhM3gzaVZ0QzU5SS1KdVBJNkdXUWF6OU1Qdm85OFJwdUJuZG4xR2dLRFR1bkltWTRuZVdfR1NaaWFtaXMxVDVtQUxCQUV0LURLRlEwMnJFWVVodkhpN3RnUUJDR1U=",
"pageInfo": {
"totalResults": 4,
"resultsPerPage": 4
},
"items": [
{
"kind": "youtube#commentThread",
"etag": "7p4LroRwZP3DTt8DuMTZoPB8WFE",
"id": "UgyHbtFESKXeYdHptoN4AaABAg",
"snippet": {
"videoId": "M7FIvfx5J10",
"topLevelComment": {
"kind": "youtube#comment",
"etag": "l7TPuxvp3y-HuT7pUTFuilRsbCo",
"id": "UgyHbtFESKXeYdHptoN4AaABAg",
"snippet": {
"videoId": "M7FIvfx5J10",
"textDisplay": "I come from the distant future and this is still the best commercial ever made",
"textOriginal": "I come from the distant future and this is still the best commercial ever made",
"authorDisplayName": "Max Haugen",
"authorProfileImageUrl": "https://yt3.ggpht.com/a/AATXAJxruw_9hJGB8nS4D2yu2j8Z-SuZ9whhaeeF1w=s48-c-k-c0xffffffff-no-rj-mo",
"authorChannelUrl": "http://www.youtube.com/channel/UCmmmb4WuHKWaXOIM5W7CNPg",
"authorChannelId": {
"value": "UCmmmb4WuHKWaXOIM5W7CNPg"
},
"canRate": true,
"viewerRating": "none",
"likeCount": 0,
"publishedAt": "2020-05-27T15:18:30Z",
"updatedAt": "2020-05-27T15:18:30Z"
}
},
"canReply": true,
"totalReplyCount": 0,
"isPublic": true
}
},
{
"kind": "youtube#commentThread",
"etag": "_gONUvfm77ZziX2qXYqMLG5ZrNY",
"id": "UgxBfriPiiexMxJSnht4AaABAg",
"snippet": {
"videoId": "M7FIvfx5J10",
"topLevelComment": {
"kind": "youtube#comment",
"etag": "6JGrrdeWCJstQ5-oN8Ll5uRxptw",
"id": "UgxBfriPiiexMxJSnht4AaABAg",
"snippet": {
"videoId": "M7FIvfx5J10",
"textDisplay": "I remember doing something similar for an English assignment back in school. What an ad",
"textOriginal": "I remember doing something similar for an English assignment back in school. What an ad",
"authorDisplayName": "Driving Channel",
"authorProfileImageUrl": "https://yt3.ggpht.com/a/AATXAJzENHoGlkmsCBbxxfoYWlnbdXVJR_B-H_FuVQ=s48-c-k-c0xffffffff-no-rj-mo",
"authorChannelUrl": "http://www.youtube.com/channel/UCF2FnoRbunwPE17Z7sB-4FQ",
"authorChannelId": {
"value": "UCF2FnoRbunwPE17Z7sB-4FQ"
},
"canRate": true,
"viewerRating": "none",
"likeCount": 0,
"publishedAt": "2020-05-27T14:27:17Z",
"updatedAt": "2020-05-27T14:27:17Z"
}
},
"canReply": true,
"totalReplyCount": 0,
"isPublic": true
}
},
{
"kind": "youtube#commentThread",
"etag": "2UZe_rxTkfikNASd6SJL_dIm3XU",
"id": "UgzdU_BTVF6gVN3UeTh4AaABAg",
"snippet": {
"videoId": "M7FIvfx5J10",
"topLevelComment": {
"kind": "youtube#comment",
"etag": "JRkp__giuGwRMX7OL-_jun2XvAU",
"id": "UgzdU_BTVF6gVN3UeTh4AaABAg",
"snippet": {
"videoId": "M7FIvfx5J10",
"textDisplay": "still the best ad ever created",
"textOriginal": "still the best ad ever created",
"authorDisplayName": "Mika Baggins",
"authorProfileImageUrl": "https://yt3.ggpht.com/a/AATXAJyUa2bJbuPGlW7fzBh8BmwdaHsjfxX2n7jUvA=s48-c-k-c0xffffffff-no-rj-mo",
"authorChannelUrl": "http://www.youtube.com/channel/UC8ydLvFnROzrIf_w60VNJuA",
"authorChannelId": {
"value": "UC8ydLvFnROzrIf_w60VNJuA"
},
"canRate": true,
"viewerRating": "none",
"likeCount": 0,
"publishedAt": "2020-05-26T20:33:47Z",
"updatedAt": "2020-05-26T20:33:47Z"
}
},
"canReply": true,
"totalReplyCount": 0,
"isPublic": true
}
},
{
"kind": "youtube#commentThread",
"etag": "FIlRkfyxEh1b94jwmiCBBvw8Zrk",
"id": "UgyJJo90JtuEgL65VTh4AaABAg",
"snippet": {
"videoId": "M7FIvfx5J10",
"topLevelComment": {
"kind": "youtube#comment",
"etag": "fj-xjtD4g21_zw4XGt9sEIG3b_Q",
"id": "UgyJJo90JtuEgL65VTh4AaABAg",
"snippet": {
"videoId": "M7FIvfx5J10",
"textDisplay": "I like it tooooooo much !!!!!!!",
"textOriginal": "I like it tooooooo much !!!!!!!",
"authorDisplayName": "В НАТУРАШКУ",
"authorProfileImageUrl": "https://yt3.ggpht.com/a/AATXAJyzs1NscDCXF_n7TnaAhkqEujQCQGHVjkabsg=s48-c-k-c0xffffffff-no-rj-mo",
"authorChannelUrl": "http://www.youtube.com/channel/UCzKl3D_2Mp25PQjVnI7zrqQ",
"authorChannelId": {
"value": "UCzKl3D_2Mp25PQjVnI7zrqQ"
},
"canRate": true,
"viewerRating": "none",
"likeCount": 0,
"publishedAt": "2020-05-26T19:08:59Z",
"updatedAt": "2020-05-26T19:08:59Z"
}
},
"canReply": true,
"totalReplyCount": 0,
"isPublic": true
}
}
]
}
答案 0 :(得分:1)
如果注释确实是一个json对象,那么将响应映射到所需的数组可能会容易得多,例如,执行以下操作:
const comments = response.items.map( comment => ({
commentId: comment.snippet.topLevelComment.id,
text: comment.snippet.topLevelComment.snippet.textDisplay })
);
这会将items
对象中的所有response
映射到新创建的注释数组中。
const response = {
"kind": "youtube#commentThreadListResponse",
"etag": "DdP0Qpu15x6rNWi8DqdtP8XHFWk",
"nextPageToken": "QURTSl9pMHRqeTI4QzlFdG9mdE44MFloNlhrS1hJS3FLSFgwS2FhM3gzaVZ0QzU5SS1KdVBJNkdXUWF6OU1Qdm85OFJwdUJuZG4xR2dLRFR1bkltWTRuZVdfR1NaaWFtaXMxVDVtQUxCQUV0LURLRlEwMnJFWVVodkhpN3RnUUJDR1U=",
"pageInfo": {
"totalResults": 4,
"resultsPerPage": 4
},
"items": [
{
"kind": "youtube#commentThread",
"etag": "7p4LroRwZP3DTt8DuMTZoPB8WFE",
"id": "UgyHbtFESKXeYdHptoN4AaABAg",
"snippet": {
"videoId": "M7FIvfx5J10",
"topLevelComment": {
"kind": "youtube#comment",
"etag": "l7TPuxvp3y-HuT7pUTFuilRsbCo",
"id": "UgyHbtFESKXeYdHptoN4AaABAg",
"snippet": {
"videoId": "M7FIvfx5J10",
"textDisplay": "I come from the distant future and this is still the best commercial ever made",
"textOriginal": "I come from the distant future and this is still the best commercial ever made",
"authorDisplayName": "Max Haugen",
"authorProfileImageUrl": "https://yt3.ggpht.com/a/AATXAJxruw_9hJGB8nS4D2yu2j8Z-SuZ9whhaeeF1w=s48-c-k-c0xffffffff-no-rj-mo",
"authorChannelUrl": "http://www.youtube.com/channel/UCmmmb4WuHKWaXOIM5W7CNPg",
"authorChannelId": {
"value": "UCmmmb4WuHKWaXOIM5W7CNPg"
},
"canRate": true,
"viewerRating": "none",
"likeCount": 0,
"publishedAt": "2020-05-27T15:18:30Z",
"updatedAt": "2020-05-27T15:18:30Z"
}
},
"canReply": true,
"totalReplyCount": 0,
"isPublic": true
}
},
{
"kind": "youtube#commentThread",
"etag": "_gONUvfm77ZziX2qXYqMLG5ZrNY",
"id": "UgxBfriPiiexMxJSnht4AaABAg",
"snippet": {
"videoId": "M7FIvfx5J10",
"topLevelComment": {
"kind": "youtube#comment",
"etag": "6JGrrdeWCJstQ5-oN8Ll5uRxptw",
"id": "UgxBfriPiiexMxJSnht4AaABAg",
"snippet": {
"videoId": "M7FIvfx5J10",
"textDisplay": "I remember doing something similar for an English assignment back in school. What an ad",
"textOriginal": "I remember doing something similar for an English assignment back in school. What an ad",
"authorDisplayName": "Driving Channel",
"authorProfileImageUrl": "https://yt3.ggpht.com/a/AATXAJzENHoGlkmsCBbxxfoYWlnbdXVJR_B-H_FuVQ=s48-c-k-c0xffffffff-no-rj-mo",
"authorChannelUrl": "http://www.youtube.com/channel/UCF2FnoRbunwPE17Z7sB-4FQ",
"authorChannelId": {
"value": "UCF2FnoRbunwPE17Z7sB-4FQ"
},
"canRate": true,
"viewerRating": "none",
"likeCount": 0,
"publishedAt": "2020-05-27T14:27:17Z",
"updatedAt": "2020-05-27T14:27:17Z"
}
},
"canReply": true,
"totalReplyCount": 0,
"isPublic": true
}
},
{
"kind": "youtube#commentThread",
"etag": "2UZe_rxTkfikNASd6SJL_dIm3XU",
"id": "UgzdU_BTVF6gVN3UeTh4AaABAg",
"snippet": {
"videoId": "M7FIvfx5J10",
"topLevelComment": {
"kind": "youtube#comment",
"etag": "JRkp__giuGwRMX7OL-_jun2XvAU",
"id": "UgzdU_BTVF6gVN3UeTh4AaABAg",
"snippet": {
"videoId": "M7FIvfx5J10",
"textDisplay": "still the best ad ever created",
"textOriginal": "still the best ad ever created",
"authorDisplayName": "Mika Baggins",
"authorProfileImageUrl": "https://yt3.ggpht.com/a/AATXAJyUa2bJbuPGlW7fzBh8BmwdaHsjfxX2n7jUvA=s48-c-k-c0xffffffff-no-rj-mo",
"authorChannelUrl": "http://www.youtube.com/channel/UC8ydLvFnROzrIf_w60VNJuA",
"authorChannelId": {
"value": "UC8ydLvFnROzrIf_w60VNJuA"
},
"canRate": true,
"viewerRating": "none",
"likeCount": 0,
"publishedAt": "2020-05-26T20:33:47Z",
"updatedAt": "2020-05-26T20:33:47Z"
}
},
"canReply": true,
"totalReplyCount": 0,
"isPublic": true
}
},
{
"kind": "youtube#commentThread",
"etag": "FIlRkfyxEh1b94jwmiCBBvw8Zrk",
"id": "UgyJJo90JtuEgL65VTh4AaABAg",
"snippet": {
"videoId": "M7FIvfx5J10",
"topLevelComment": {
"kind": "youtube#comment",
"etag": "fj-xjtD4g21_zw4XGt9sEIG3b_Q",
"id": "UgyJJo90JtuEgL65VTh4AaABAg",
"snippet": {
"videoId": "M7FIvfx5J10",
"textDisplay": "I like it tooooooo much !!!!!!!",
"textOriginal": "I like it tooooooo much !!!!!!!",
"authorDisplayName": "В НАТУРАШКУ",
"authorProfileImageUrl": "https://yt3.ggpht.com/a/AATXAJyzs1NscDCXF_n7TnaAhkqEujQCQGHVjkabsg=s48-c-k-c0xffffffff-no-rj-mo",
"authorChannelUrl": "http://www.youtube.com/channel/UCzKl3D_2Mp25PQjVnI7zrqQ",
"authorChannelId": {
"value": "UCzKl3D_2Mp25PQjVnI7zrqQ"
},
"canRate": true,
"viewerRating": "none",
"likeCount": 0,
"publishedAt": "2020-05-26T19:08:59Z",
"updatedAt": "2020-05-26T19:08:59Z"
}
},
"canReply": true,
"totalReplyCount": 0,
"isPublic": true
}
}
]
};
const comments = response.items.map( comment => ({ commentId: comment.snippet.topLevelComment.id, text: comment.snippet.topLevelComment.snippet.textDisplay }) );
console.log( comments );
如果我们查看您提供的代码,则需要注意一些事项,尽管我知道它可能是比实际代码更简单的版本
不应将注释的声明和初始化保留在数组范围之外,因为您打算使用它。如果以这种方式执行操作,并且数组将填充,则所有注释将指向一个对象,并且具有相同的属性(始终保持相同的引用)
var comment = {
Comment_ID : "",
Text_Displayed : ""
};
您将total定义为硬编码4,尽管这可能当前有效,但您手头有更好的选择。数组具有length
属性,因此最好改用该数组
const total = json1.items.length;
i
仅在for循环中使用,因此您最好仅在for循环中声明它,因此,它变成了这样的样子(重新编写了如何添加注释而不重新使用变量)
for( let i = 0 ; i < total ; i++) {
comments.push({
Comment_ID: json1.items[i].snippet.topLevelComment.id,
Text_Displayed: json1.items[i].snippet.topLevelComment.snippet.textDisplay
});
}
但是,您仍然拥有索引访问权限,可以使用我给您显示的地图或使用类似以下内容的for..of
循环来进行此操作:
for( let comment of json1.items ) {
comments.push({
Comment_ID: comment.snippet.topLevelComment.id,
Text_Displayed: comment.snippet.topLevelComment.snippet.textDisplay
});
}
因此使您的代码更具可读性。毫无疑问,您在我的所有更改中都使用了let
和const
关键字。它们是在JS 2015中引入的(我认为,必须跟进),它们确实值得使用。应尽可能避免使用var
,因为let
和const
可以纠正var
关键字带来的范围问题