Search code examples
javascriptjavascript-objects

Avoid repetition of code during data conversion


I have some dummy data like below:

data: {
    first: {
        date_2019_01: 10,
        date_2019_02: 15,
        ....
    },
    second: {
        date_2019_01: 30,
        date_2019_02: 35,
        ....
    }
}

I have to convert this initial data into following format where date as key is to converted to month and its value as growth.

first: [
    {
        month: 1,
        growth: 10
    },
    {
        month: 2,
        growth: 15
    },
    ...
],
second: [
    {
        month: 1,
        growth: 30
    },
    {

    }
]

In my solution I get the keys and split it to get my desired month which is pushed to new array. But here my codes are repeated. I am learning on quality of code which includes DRY concept as well.

Please anybody help me write this piece of code in better format.

Thank You.

let first = data["first"];

let firstMonth = [];
Object.keys(first).map(function(key) {
    firstMonth.push({
        month: key.split('_')[2],
        growth: first[key]
    });
});

let second = data["second"];

let secondMonth = [];
Object.keys(second).map(function(key) {
    secondMonth.push({
        month: key.split('_')[2],
        growth: second[key]
    });
});

let finalData = {
    first: firstMonth,
    second: secondMonth
}

Solution

  • One option is a .map inside a .reduce. You can use Object.entries instead of Object.keys to retrieve both the keys and values at once, which will cut down a bit on the amount of syntax needed:

    const data = {
        first: {
            date_2019_01: 10,
            date_2019_02: 15,
        },
        second: {
            date_2019_01: 30,
            date_2019_02: 35,
        }
    };
    const newData = Object.entries(data).reduce((a, [key, obj]) => {
      a[key] = Object.entries(obj).map(([key, growth]) => ({
        month: Number(key.slice(10)),
        growth
      }));
      return a;
    }, {});
    console.log(newData);