I have an array of objects and I was trying to figure out how I can create a new array of objects that would display a new array of objects, but with an "occurences" field.
Here is my starting json array of objects:
const fakeJson = [
{
"Id": 1,
"Name": "John",
"Age": 32,
"Date_Available": "2022-04-10",
"Popularity": 99,
"Country": "Canada"
},
{
"Id": 1,
"Name": "John",
"Age": 32,
"Date_Available": "2022-04-11",
"Popularity": 99,
"Country": "Canada"
},
{
"Id": 1,
"Name": "John",
"Age": 32,
"Date_Available": "2022-04-12",
"Popularity": 99,
"Country": "Canada"
},
{
"Id": 1,
"Name": "John",
"Age": 32,
"Date_Available": "2022-04-12",
"Popularity": 99,
"Country": "China"
},
{
"Id": 1,
"Name": "John",
"Age": 32,
"Date_Available": "2022-04-12",
"Popularity": 99,
"Country": "Canada"
}
Example result of what I would like. Notice the for Country Canada, one of them has Occurences: 2 for Date_Available "2022-04-12". How would I be able to accomplish this?
const resultJSON = [
{
"Date_Available": "2022-04-10",
"Popularity": 99,
"Country": "Canada",
"Occurrences" : 1
},
{
"Date_Available": "2022-04-11",
"Popularity": 99,
"Country": "Canada",
"Ocurrences" : 1
},
{
"Date_Available": "2022-04-12",
"Popularity": 99,
"Country": "Canada",
"Occurrences" : 2
},
{
"Date_Available": "2022-04-12",
"Popularity": 99,
"Country": "China",
"Occurrences" : 1
}
Here is what I have so far. My idea was to create a temporary obj with the country name, date available and occurrence set default to 1. Then based on the Date_Available, increase by 1 every time it appeared. However, if China and Canada both have the same date, then it seems to mess up the code and does not properly print the result.
let countNameMapping = {};
let finalArr = [];
for(let i = 0; i < fakeJson.length; i++){
let tempObj = {Country:fakeJson[i].Country, Date_Available: fakeJson[i].Date_Available, occurence: 1};
let countryName = fakeJson[i].Country;
let date = fakeJson[i].Date_Available;
if(countNameMapping[date] === undefined){
countNameMapping[countryName] = tempObj;
} else {
countNameMapping[date].occurence += 1;
}
}
for(let k in countNameMapping){
finalArr.push(countNameMapping[k])
}
console.log(finalArr)