【问题标题】:Angular: group by field while displaying from json using *ngForAngular:使用 *ngFor 从 json 显示时按字段分组
【发布时间】:2019-09-01 20:46:12
【问题描述】:

我想通过 JSON 下面的“工作”为机组人员显示为组。 例如:导演是一位,但制片人不止一位,但想表现得像:

生产者:生产者1、生产者2、生产者3

原创音乐作曲家:composer1、composer2

等等。 我想用 *ngFor 将它们分组到 html 视图中,可能类似于

<ul *ngFor="let group of crew">
  <li>{{group.job}}</li>
  <ul>
     <li *ngFor="let crews of group.name">
      {{crews.name}}
     </li>
  </ul>
</ul>

没有分组的工作演示: https://stackblitz.com/edit/angular-ttfieu 例如,我需要对制作人和演员进行分组。

JSON 是:

"crew": [
    {
      "credit_id": "56380f0cc3a3681b5c0200be",
      "department": "Writing",
      "gender": 0,
      "id": 7469,
      "job": "Screenplay",
      "name": "Jim Uhls",
      "profile_path": null
    },
    {
      "credit_id": "52fe4250c3a36847f8014a05",
      "department": "Production",
      "gender": 0,
      "id": 7474,
      "job": "Producer",
      "name": "Ross Grayson Bell",
      "profile_path": null
    },
    {
      "credit_id": "52fe4250c3a36847f8014a0b",
      "department": "Production",
      "gender": 0,
      "id": 7475,
      "job": "Producer",
      "name": "Ceán Chaffin",
      "profile_path": null
    },
    {
      "credit_id": "52fe4250c3a36847f8014a11", 
      "department": "Production",
      "gender": 0,
      "id": 1254,
      "job": "Producer",
      "name": "Art Linson",
      "profile_path": "/dEtVivCXxQBtIzmJcUNupT1AB4H.jpg"
    },
    {
      "credit_id": "52fe4250c3a36847f8014a17",
      "department": "Sound",
      "gender": 0,
      "id": 7477,
      "job": "Original Music Composer",
      "name": "John King",
      "profile_path": null
    },
    {
      "credit_id": "52fe4250c3a36847f8014a29",
      "department": "Editing",
      "gender": 0,
      "id": 7480,
      "job": "Editor",
      "name": "James Haygood",
      "profile_path": null
    },
    {
      "credit_id": "52fe4250c3a36847f8014a2f",
      "department": "Production",
      "gender": 0,
      "id": 7481,
      "job": "Casting",
      "name": "Laray Mayfield",
      "profile_path": null
    },

组件:

import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { ActivatedRoute } from '@angular/router';
import { MoviesService } from '../movies.service';

    @Component({
      selector: 'app-crew',
      templateUrl: './crew.component.html',
      styleUrls: ['./crew.component.css']
    })
    export class CrewComponent implements OnInit {
      movie: Object;
      crew: Array<Object>;

      constructor(
        private _moviesServices: MoviesService,
        private router: ActivatedRoute
      ) {
      }
      ngOnInit() {
        this.router.params.subscribe((params) => {
          const id = params['id'];
          this._moviesServices.getMovie(id).subscribe(movie => {
            this.movie = movie;
          });
          this._moviesServices.getMovieCredits(id).subscribe((res: any) => {
            res.crew = res.crew.filter((item) => { return item.job });
            console.log(res)
            this.crew = res.crew;
          });
    })
  }
}

html模板是:

<div class="row mt-3" *ngIf="crew && crew.length > 0">
<div class="col">
    <h3>Crew</h3>
    <div class="row flex-nowrap overflow-auto">
        <div class="col-lg-3 col-4 col-md-3 col-sm-2" *ngFor="let actor of crew">
            <div class="card bg-dark">
                <a routerLink="/crew/{{actor.id}}">
                    <img *ngIf="actor.profile_path" src="https://image.tmdb.org/t/p/w500/{{actor.profile_path}}"
                        alt="{{actor.name}}" class="card-img-top">
                    <img *ngIf="!actor.profile_path" src="../../assets/noimage.png" alt="{{actor.name}}"
                        class="card-img-top">
                    <div class="card-body">
                        <span class="text-white"> {{actor.name}}</span>
                    </div>
                </a>
            </div>
        </div>
    </div>
</div>

提前谢谢你

【问题讨论】:

  • 您可以通过job 回复filter。例如,this.producers = res.filter(c =&gt; c.job.toLowerCase() === 'producer'); 和作曲家也一样。
  • 是的,我可以,但所有这些领域都可以这样做
  • 我正在寻找使用 ngFor 分组的 angular 2 向前可能的解决方案

标签: angular angular8 themoviedb-api


【解决方案1】:

编辑后将作业值作为分组对象的属性键


尝试使用这个并按job分组:

function groupBy(collection, property) {
   var i = 0, val, index,
        values = [], result = [];
    for (; i < collection.length; i++) {
        val = collection[i][property];
        index = values.indexOf(val);
        if (index > -1)
            result[val].push(collection[i]);
        else {
            values.push(val);
            result[val] = [];
            result[val].push([collection[i]]);
        }
    }
    return result;
}

var obj = groupBy(yourArray, "job");

参考这篇 SO 帖子:javascript | Object grouping

Here's a working example on StackBlitz

【讨论】:

  • 感谢您的回复;我想使用 ngFor 在角度视图中执行此操作。
  • 我在答案中添加了 Stackblitz 链接。让我知道这是否有任何好处
  • 过滤res.crew时不知道你想做什么。尝试提供您实际场景的 Stackblitz。此外,这与您最初的问题有所不同,因为我相信我给出的答案确实回答了它。
  • 已修复,非常感谢您,很抱歉造成混淆。这就是我想做的:this.obj = this.groupBy(res.crew, "job");
  • 很高兴你自己弄明白了 :) 当你自己理解它并设法让它工作时总是更好!
猜你喜欢
  • 1970-01-01
  • 2019-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
  • 2019-05-02
  • 2020-12-14
相关资源
最近更新 更多