Reputation: 3209
I am trying to create an archive system from google blogger api. I have the data as json of all posts from the blogger. Here is my code that I have tried.
var archive= {};
if("entry" in TotalFeed.feed)
{
var PostEntries=TotalFeed.feed.entry.length;
for(var PostNum=0; PostNum<PostEntries ; PostNum++)
{
var ThisPost = TotalFeed.feed.entry[PostNum];
var key=ThisPost.published.$t.substring(0,4);
var MonthNames=["January","February","March","April","May","June","July","August","September","October","November","December"];
var m=ThisPost.published.$t.substring(5,7);
var NameOfMonth = MonthNames[parseInt(m)-1];
archive[key] = {
[NameOfMonth]: 1
}
}
}
console.log(archive);
The result of this code is
2011:{May: "1"},
2012:{January: "1"},
2013:{January: "1"}
There are many months in 2011 but you can see it only overwrite the last one. So I only get last month of the year from the loop. How can I get all the months listed?
Any idea or help is highly appreciated. Thank you.
Edit: Key is not same, Here is a picture of the log
Upvotes: 0
Views: 103
Reputation: 171698
You need a deeper object and you are also not checking if archive[key]
already exists so you overwrite it if it does.
Try something like
// existing year object or create it
archive[key] = archive[key] || {};
//existing month array or create it
archive[key][NameOfMonth] = archive[key][NameOfMonth] || [];
// push item to appropriate month array
archive[key][NameOfMonth].push(ThisPost)
Or just to count year/month entries:
// existing year object or create it
archive[key] = archive[key] || {};
//existing month property or create it then increment count
archive[key][NameOfMonth] = (archive[key][NameOfMonth] || 0) +1;
Upvotes: 1