Avoid repetition of code during data conversion

nas*_*nas 1 javascript javascript-objects

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,
        ....
    }
}
Run Code Online (Sandbox Code Playgroud)

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
    },
    {

    }
]
Run Code Online (Sandbox Code Playgroud)

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.

请任何人帮助我以更好的格式编写这段代码。

谢谢。

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
}
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 5

一种选择是.map在内.reduce。您可以使用Object.entries而不是Object.keys一次检索键和值,这将减少所需的语法量:

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);
Run Code Online (Sandbox Code Playgroud)