Skip to content
Advertisement

Change object label on specific value in js

I’m working on charts in React.js and i want to display data sorted by month. In django i’ve created view for displaying json with total events per month and it looks like this:

    [
        {
            "month": "2022-06-01T00:00:00+02:00",
            "total": 4
        },
        {
            "month": "2022-08-01T00:00:00+02:00",
            "total": 1
        }
    ]
]

I would like to sort every object in that array and change value ‘month’ from numbers to month name, so it would be:

    [
        {
            "month": "june",
            "total": 4
        },
        {
            "month": "august",
            "total": 1
        }
    ]
]

For generating charts i’m using chartist.

Advertisement

Answer

You could store the full date as a seperate key (called date), and set the month in a seperate function using a predefined array for the names of each month. Here is the code you would use:

const monthName = ["January", "February", "March", "April", "May", "June",     
"July", "August", "September", "October", "November", "December"]; // Array representing each month

var chartItems = [
    {
        "date": "2022-06-01T00:00:00+02:00",
        "month": null,
        "total": 4
    },
    {
        "date": "2022-08-01T00:00:00+02:00",
        "month": null,
        "total": 1
    }
];

// Run through each item in the array
function setMonths(arr) {
    arr.forEach(item => {
        const date = new Date(item.date); // Convert date string to Date object
        const monthIndex = date.getMonth(); // Get index of month from the Date
        const month = monthName[monthIndex]; // Convert index into text representing the month

        item.month = month; // Set the month key in the object to the new month
    });
}

setMonths(chartItems); // Call function to set months in the array

As an alternative, you could also make a method for each object in the array that gets the month, but you would need to run this everytime you want to get the month. Here is the code for that:

const monthName = ["January", "February", "March", "April", "May", "June",     
"July", "August", "September", "October", "November", "December"];

var chartItems = [
    {
        "date": "2022-06-01T00:00:00+02:00",
        "month": function() { return monthName[new Date(this.date).getMonth()]; },
        "total": 4
    },
    {
        "date": "2022-08-01T00:00:00+02:00",
        "month": function() { return monthName[new Date(this.date).getMonth()]; },
        "total": 1
    }
];

And you would get it like this:

chartItems[0].month(); // "[0]", meaning the first item in the array
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement