i have bellow object array
var dataarray = [
{
"Country": "America",
"Total": 200,
"Month" : "Jan"
},
{
"Country": "America",
"Total": 100,
"Month" : "Feb"
},
{
"Country": "India",
"Total": 100,
"Month" : "Feb"
}
]
from there what im expecting is like bellow
var final_array [
{"Country" : "America",
"Jan": 200,
"Feb" : 100
},
{"Country" : "India",
"Jan": 0,
"Feb" : 100
}
]
for some country not all the month will be there. only the month with data will be retrieved but in the final result if the month not present in original array the value should 0. like the above same array
i tried something like bellow but not able continue further as I’m not able to implement it
dataarray.forEach(entry => {
let line = result.find(resultEntry => resultEntry.Country=== entry.Country);
if (line) {
result = result.filter(resultEntry => resultEntry.Country!== line.Country);
result.push({ ...entry, ...line })
} else {
result.push(entry)
}
});
2
Answers
This code should produce the desired output as shown in your final_array example. It iterates through the dataarray, builds the new structure, and then ensures that all months are present with their respective values, filling in missing months with zeros.
javascript
Create an object with all the available month names set as the as key name, and its value set to zero.
Create another object with the country names as keys with their initial value an object spreading out the
months
object to get their initial values. Then add the the months and totals to the object using theCountry
value.Additional documentation
Object.values
Nullish Coalescing Assignment (
??=
)