как превратить объект массивов в массив объектов? - PullRequest
0 голосов
/ 28 мая 2020

структура данных, которые получает ax ios:

{
    "data": {
        "project": {
            "id": "5ebd525ea3ff2434c0d467f8",
            "items": [
                {
                    "name": "item one",
                    "size": 45,
                    "createdAt": "2020-05-14T14:15:43.034Z",
                },
                {
                    "name": "item two",
                    "size": 23,
                    "createdAt": "2020-05-14T14:15:58.508Z",
                },
                {
                    "name": "item one",
                    "size": 93,
                    "createdAt": "2020-05-14T15:02:19.889Z"
                },
                {
                    "name": "item two",
                    "size": 55,
                    "createdAt": "2020-05-19T02:48:14.486Z"
                }
            ]
        }
    }
}

Мне нужно выполнить sh это две вещи:

  • Группировать элементы по имени
  • сопоставление с новыми массивами для рендеринга на диаграмме

код, который у меня есть:

async created() {
      const response = await axios.get(
        `http://localhost:1337/projects/${this.routeId}`
      ))
      const { items } = response.data

  //returns new array of only fields needed to send to the chart
      const newArray = items.map(({name, size, createdAt}) => ({name, size, createdAt}))

 // group items by name **** this creates an object of arrays
      const groupBy = (array, key) => {
        return array.reduce((result, currentValue) => {
          (result[currentValue[key]] = result[currentValue[key]] || [])
          .push(currentValue);
          return result
        }, {})
      };
      const itemsGroupedByName = groupBy(newArray, 'name')

  //this fails *** trying to map an object into a new array
      itemsGroupByName.forEach(d => {
        const { name, size, createdAt } = d
        this.arrItemSize.push({
          date: moment(createdAt).format('MMM D YYYY'),
          total: size,
          name
        })
      })
    },

Приведенный выше код группирует элементы как объект массивов -

{ [...], [...], [...], [...] }

Формат, необходимый диаграмме, - это массив объектов

[ {...}, {...}, {...}, {...]

Как сопоставить сгруппированные элементы новым массивам? Спасибо за любую помощь

1 Ответ

0 голосов
/ 28 мая 2020

Вы можете использовать функцию Array.prototype.reduce для группировки и функцию Object.values для извлечения сгруппированных объектов.

Предполагается, что свойство items будет содержать сгруппированные объекты.

let obj = {        "data": {            "project": {                "id": "5ebd525ea3ff2434c0d467f8",                "items": [                    {                        "name": "item one",                        "size": 45,                        "createdAt": "2020-05-14T14:15:43.034Z",                    },                    {                        "name": "item two",                        "size": 23,                        "createdAt": "2020-05-14T14:15:58.508Z",                    },                    {                        "name": "item one",                        "size": 93,                        "createdAt": "2020-05-14T15:02:19.889Z"                    },                    {                        "name": "item two",                        "size": 55,                        "createdAt": "2020-05-19T02:48:14.486Z"                    }                ]            }        }    };
let result = Object.values(obj.data.project.items.reduce((a, {name, ...rest}) => {
  (a[name] || (a[name] = {items: []}))["items"].push({name, ...rest});
  return a;
}, Object.create(null)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...