Reputation: 65
I am trying to push objects into an array of objects. The code I have written repeats the last index value for all indices in the array. Any help regarding what I might be doing wrong would be great.
CODE:
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 is the raw JSON response. I have tried parsing it using JSON.parse(json1) and thus converting it to a Javascript object, however, doing so, my array remains empty.
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
}
}
]
}
Upvotes: 1
Views: 80
Reputation: 12806
If comments is indeed a json object, then you might be far easier of to map the response to the array you need, for example by doing:
const comments = response.items.map( comment => ({
commentId: comment.snippet.topLevelComment.id,
text: comment.snippet.topLevelComment.snippet.textDisplay })
);
This will map all the items
in the response
object into a newly created comments array.
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 );
If we look at the code you provided, there are some things you need to be careful with, albeit I get that it's probably a simpler version than the actual code you have
The declaration and initialization of comment shouldn't be kept out of the scope of array, as you intend to use it. If you do it this way, and the array would fill, all comments would refer to the one single object, and would have the same properties (it stays always the same reference)
var comment = {
Comment_ID : "",
Text_Displayed : ""
};
You define total to be a hardcoded 4, and while this might currently work, you have better options at hand. An array has a length
property, so it seems better to use that one instead
const total = json1.items.length;
i
will only be used in the for-loop, so you might as well declare it there only, thus, it becomes something like this (with a rework how you could add the comments without re-using a variable)
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
});
}
however, you still have the index accesses, and this you could for go by using the map I showed you, or by using a for..of
loop like:
for( let comment of json1.items ) {
comments.push({
Comment_ID: comment.snippet.topLevelComment.id,
Text_Displayed: comment.snippet.topLevelComment.snippet.textDisplay
});
}
Thus making your code a little bit more readable. You undoubtedly noticed the usage of let
& const
keywords throughout my changes. They were introduced in JS 2015 (I think, have to follow up) and they are really worthy to use. var
should be avoided whenever possible, as let
& const
are there to rectify the scope problems that the var
keyword carries
Upvotes: 1