Добавить отсутствующие значения в сгруппированные данные - PullRequest
1 голос
/ 07 мая 2020

Это продолжение моего вопроса . Я получаю сгруппированное значение по дате из массива объектов. Когда я группирую значения, могу ли я заполнить метрику c как 0 при группировке по дате для отсутствующих типов в день.

Это мой массив:

arr = [
        {
           "date": "2020-01-01",
           "metric": 32,
           "type": "Google"
        },
        {
           "date": "2020-01-01",
           "metric": 24,
           "type": "Bing"
        },
        {
           "date": "2020-01-02",
           "metric": 1,
           "type": "Google"
        },
        {
           "date": "2020-01-02",
           "metric": 32,
           "type": "Jeeves"
        },
        {
           "date": "2020-01-03",
           "metric": 24,
           "type": "Bing"
        },
        {
           "date": "2020-01-03",
           "metric": 30,
           "type": "Google"
        }
    ]

Вот как я группирую данные:

const groupBy = (array, key) => {
    return array.reduce((result, currentValue) => {
      (result[currentValue[key]] = result[currentValue[key]] || []).push(currentValue);
      return result;
    }, {});
};

const personGroupedByColor = groupBy(arr, 'date');

Мой результат:

2020-01-01: 
0: {date: "2020-01-01", metric: 32, type: "Google"}
1: {date: "2020-01-01", metric: 24, type: "Bing"}
2020-01-02: 
0: {date: "2020-01-02", metric: 1, type: "Google"}
1: {date: "2020-01-02", metric: 32, type: "Jeeves"}
2020-01-03: 
0: {date: "2020-01-03", metric: 24, type: "Bing"}
1: {date: "2020-01-03", metric: 30, type: "Google"}

Есть ли способ получить:

2020-01-01: 
0: {date: "2020-01-01", metric: 32, type: "Google"}
1: {date: "2020-01-01", metric: 24, type: "Bing"}
2: {date: "2020-01-01", metric: 0, type: "Jeeves"}
2020-01-02: 
0: {date: "2020-01-02", metric: 1, type: "Google"}
1: {date: "2020-01-02", metric: 0, type: "Bing"}
2: {date: "2020-01-02", metric: 32, type: "Jeeves"}
2020-01-03: 
0: {date: "2020-01-03", metric: 30, type: "Google"}
1: {date: "2020-01-03", metric: 24, type: "Bing"}
2: {date: "2020-01-03", metric: 0, type: "Jeeves"}

Могу ли я заменить отсутствующие значения на метри c из 0 ?

1 Ответ

2 голосов
/ 07 мая 2020

Вы можете создать Set всех различных type значений, затем перебрать каждое значение в personGroupedByColor, проверяя, что они имеют все разные type значения, а если нет, нажав новый объект с этим типом и метрикой c из 0:

arr = [{
    "date": "2020-01-01",
    "metric": 32,
    "type": "Google"
  },
  {
    "date": "2020-01-01",
    "metric": 24,
    "type": "Bing"
  },
  {
    "date": "2020-01-02",
    "metric": 1,
    "type": "Google"
  },
  {
    "date": "2020-01-02",
    "metric": 32,
    "type": "Jeeves"
  },
  {
    "date": "2020-01-03",
    "metric": 24,
    "type": "Bing"
  },
  {
    "date": "2020-01-03",
    "metric": 30,
    "type": "Google"
  }
]

const groupBy = (array, key) => {
  return array.reduce((result, currentValue) => {
    (result[currentValue[key]] = result[currentValue[key]] || []).push(currentValue);
    return result;
  }, {});
};

let personGroupedByColor = groupBy(arr, 'date');

const types = new Set(arr.map(a => a.type));

for (a in personGroupedByColor) {
  types.forEach(t => {
    if (!personGroupedByColor[a].some(v => v.type == t)) {
      personGroupedByColor[a].push({
        "date": personGroupedByColor[a][0].date,
        "metric": 0,
        "type": t
      });
    }
  })
}
console.log(personGroupedByColor);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...