Search code examples
javascriptarraysjavascript-objects

how to turn a daily data object into a monthly object


so i have a question how to turn this object :

let data = [
{"branch": "london", "date": "2020-05-07", "sales": 500},
{"branch": "london", "date": "2020-05-08", "sales": 1500},
{"branch": "london", "date": "2020-05-09", "sales": 1000},
{"branch": "london", "date": "2020-06-09", "sales": 1000},
{"branch": "wales", "date": "2020-05-10", "sales": 2000},
{"branch": "wales", "date": "2020-05-11", "sales": 3000},
{"branch": "wales", "date": "2020-06-12", "sales": 2500},
{"branch": "wales", "date": "2020-08-12", "sales": 1500}
]

into that object :

let monthlyData = [
{"branch": "london", "date": "2020-05", "sales": 3000},
{"branch": "london", "date": "2020-06", "sales": 1000},
{"branch": "wales", "date": "2020-05", "sales": 5000},
{"branch": "wales", "date": "2020-06", "sales": 2500},
{"branch": "wales", "date": "2020-08", "sales": 1500},
]

so my goal here is to have every branch give me a monthly record instead of daily how to solve this as I have only managed to do it but with the date and sales expanding the current object instead of creating a new one with the new month data.


Solution

  • i solved the issue by using 2 for each loops

    let data = [
        {"branch": "london", "date": "2020-05-07", "sales": 500},
        {"branch": "london", "date": "2020-05-08", "sales": 1500},
        {"branch": "london", "date": "2020-05-09", "sales": 1000},
        {"branch": "london", "date": "2020-06-09", "sales": 1000},
        {"branch": "wales", "date": "2020-05-10", "sales": 2000},
        {"branch": "wales", "date": "2020-05-11", "sales": 3000},
        {"branch": "wales", "date": "2020-05-12", "sales": 2100},
        {"branch": "wales", "date": "2020-06-12", "sales": 2500},
        {"branch": "wales", "date": "2020-08-12", "sales": 1500},
        {"branch": "wales", "date": "2020-09-12", "sales": 200},
    ]
    monthlyData = []
    
    data.forEach((dataSet) => {
        if (monthlyData.length === 0) {
            newObj = {
                "branch": dataSet.branch,
                "date": dataSet.date.substring(0,7),
                "sales": dataSet.sales
            }
            monthlyData.push(newObj)
        } else {
            let found = false
            monthlyData.forEach((month) => {
                if (month.branch === dataSet.branch && month.date === dataSet.date.substring(0,7)) {
                    month.sales += dataSet.sales
                    found = true
                }
            })
            if (!found) {
                newObj = {
                    "branch": dataSet.branch,
                    "date": dataSet.date.substring(0,7),
                    "sales": dataSet.sales
                }
                monthlyData.push(newObj)
            }
        }
    })