首页 > 解决方案 > Angular 10:如何比较两个数组

问题描述

我有两个数组,一个带有颜色,一个带有类别。

"colors": [
        {
          "buttonId": "color-cinder-spark-red",
          "filmCategory": 1,
          "name": "cinder spark red",
          "previewImg": "assets/filmPreviewImg/gloss-cinder-spark-red.png",
          "default": true
        },
        {
          "buttonId": "color-gloss-red-metallic",
          "filmCategory": 2,
          "name": "red metallic",
          "previewImg": "assets/filmPreviewImg/gloss-red-metallic.png"
        },
        {
          "buttonId": "color-dragon-red",
          "filmCategory": 3,
          "name": "dragon red",
          "previewImg": "assets/filmPreviewImg/gloss-dragon-red.png"
        },...

数组非常大。

这里是分类:

"types": [
        {
          "id": 1,
          "name": "Gloss",
          "type": "gloss"
        },
        {
          "id": 2,
          "name": "Matte",
          "type": "matte",
          "default": true
        },
        {
          "id": 3,
          "name": "Satin",
          "type": "satin"
        },...

在颜色数组中,类别显示为 id。我需要将所选颜色的id与类别进行比较,然后获取类别的名称。在这里我将获取所选颜色的类别 id

  filmTypes = filmTypes.types;
  filmColors = filmColors.colors;

  currentColor: any;
 
  modalRef: BsModalRef;
  constructor(private modalService: BsModalService,
              private _productService: ProductService) {}

  ngOnInit(): void {
    const defaultColor = this.filmColors.find((c) => c.default);
    this.selectColor(defaultColor);  
       
    this._productService.currentFilmColor$.subscribe((color: any) => {      
      this.currentColor = color.filmCategory;          
      console.log('color2',this.currentColor);            
    });    
  }

如何在另一个数组中比较这个 id 并获取类别名称?

标签: javascriptangular

解决方案


使用Array#find.

const { name } = filmTypes.find(({ id }) => id === this.currentColor);

推荐阅读