Группировать массив данных JSON в другой массив - PullRequest
0 голосов
/ 18 сентября 2019

Я создаю приложение Angular 7.В этом приложении я получаю данные JSON с сервера, которые затем хочу сгруппировать по определенному ключу.Мне удалось это сделать, но у меня уже не массив, а какой-то объект.

Начальные данные JSON

[{
    "id": 67,
    "survey_id": 26,
    "question_id": 63,
    "user_id": 35,
    "privacy": null,
    "score": null,
    "comment": "A nice little comment",
    "binary": null,
    "reasons": null,
    "preferences": "{}",
    "created_at_date": "2019-09-18",
    "created_at_time": "19:53",
    "user": {
        "id": 35,
        "fullname": "Michael Palin"
    },
    "can_manage": true
},
{
    "id": 68,
    "survey_id": 26,
    "question_id": 64,
    "user_id": 4,
    "privacy": null,
    "score": null,
    "comment": "Another little comment",
    "binary": null,
    "reasons": null,
    "preferences": "{}",
    "created_at_date": "2019-09-18",
    "created_at_time": "19:53",
    "user": {
        "id": 4,
        "fullname": "Roland Smacker"
    },
    "can_manage": true
},
{
    "id": 69,
    "survey_id": 26,
    "question_id": 65,
    "user_id": 4,
    "privacy": null,
    "score": null,
    "comment": "Some more comments",
    "binary": null,
    "reasons": null,
    "preferences": "{}",
    "created_at_date": "2019-09-18",
    "created_at_time": "19:53",
    "user": {
        "id": 4,
        "fullname": "Roland Smacker"
    },
    "can_manage": true
},
{
    "id": 70,
    "survey_id": 26,
    "question_id": 66,
    "user_id": 4,
    "privacy": null,
    "score": 5,
    "comment": null,
    "binary": null,
    "reasons": null,
    "preferences": "{}",
    "created_at_date": "2019-09-18",
    "created_at_time": "19:53",
    "user": {
        "id": 4,
        "fullname": "Roland Smacker"
    },
    "can_manage": true
}

]

Это мой код группировки

setupStats() {
    const groupBy = (array, key) => {
      return array.reduce((result, currentValue) => {
        (result[currentValue[key]] = result[currentValue[key]] || []).push(
          currentValue
        );
        return result;
      }, {});
    };
    const grouped = groupBy(this.collection, 'user_id');
    console.log(grouped);
  }

Это вывод

{4: Array(3), 35: Array(1)}

4 и 35 - это user_ids.Я хотел бы, чтобы они получили части массива, чтобы я мог зациклить их, что я не могу сделать сейчас.

Ответы [ 2 ]

1 голос
/ 18 сентября 2019

Если вы хотите связать свои сгруппированные данные с шаблоном с помощью директивы *ngFor, вы можете использовать канал keyvalue для перебора вашего объекта группировки:

<div *ngFor="let group of groupedItems | keyvalue">
  <strong>{{ group.key }} {{ group.value.length }} items</strong>
  <div *ngFor="let item of group.value">
    {{item.id}} {{item.comment}}
  </div>
</div>

Вы можете прочитатьо значении трубы здесь .

1 голос
/ 18 сентября 2019

Вы можете использовать простой цикл, чтобы сделать эту группировку, что-то вроде этого:

const arr = [{
    "id": 67,
    "survey_id": 26,
    "comment": "A nice little comment",
    "user": {
        "id": 35,
        "fullname": "Michael Palin"
    },
    "can_manage": true
},
{
    "id": 68,
    "survey_id": 26,
    "user": {
        "id": 4,
        "fullname": "Roland Smacker"
    },
    "can_manage": true
},
{
    "id": 69,
    "survey_id": 26,
    "user": {
        "id": 4,
        "fullname": "Roland Smacker"
    },
    "can_manage": true
},
{
    "id": 70,
    "survey_id": 26,
    "user": {
        "id": 4,
        "fullname": "Roland Smacker"
    },
    "can_manage": true
}];

const map = {};

for(const item of arr) {
  const id = item.user.id;
  if(!map[id]) {
    map[id] = [];
  }
  
  map[id].push(item);
}

// Access specific group by id.
// console.log(map['4']);

// Loops over all the groups.
for(const [id, groupArr] of Object.entries(map)) {
  console.log('id: ' + id);
  console.log('associated array: ', groupArr);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...