将Object数组值与其他对象值映射

时间:2019-04-17 06:52:12

标签: angular typescript

使用cat对象中的cat名称字符串值映射prod对象的cat id。 我想用字符串cat在HTML中显示产品。

var prod = [
    { name: "Necklace", cat: [1, 2, 3] },
    { name: "Bindi", cat: [2, 4] }
]

var cat = [
    { id: 1, name: "gold" },
    { id: 2, name: "silver" },
    { id: 3, name: "platinum" },
    { id: 4, name: "copper" }
]

prod.forEach((p) => {
    p.cat.forEach((c) => {
        cat.filter((d) => {
            if (c == d.id) {
                //logic to display cat of prod in string
            }
        })
    })
})

HTML:

<ul class="flex-container">
    <li *ngFor="let product of prod">
        <label>Name-{{product.name}}</label><br>
        <label>cat-{{product.cat}}</label>
    </li>
</ul>

实际输出:

Name-Necklace
cat-[1,2,3]

Name-Bindi
cat-[2,4]

预期输出:

Name-Necklace
cat-gold,silver,platinum

Name-Bindi
cat-silver,copper

2 个答案:

答案 0 :(得分:0)

您可以使用Angular Pipe轻松过滤猫。然后是有角度的方式。

Working Demo

cat-filter.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'catFilterPipe'
})

export class CatFilterPipe implements PipeTransform {
  transform(items: any[], field: any, value: any): any[] {
    if (!items) return [];
    if (!value) return items;

    return items.filter(it =>  value.indexOf(it[field]) > -1);

  }
}

组件TS

export class AppComponent {
  public prod = [{ name: "Necklace", cat: [1, 2, 3] }, {
    name: "Bindi", cat: [2, 4]
  }]

  public cat = [{ id: 1, name: "gold" }, { id: 2, name: "silver" }, {
    id: 3, name: "platinum"
  }, { id: 4, name: "copper" }]


}

组件HTML

<ul class="flex-container">
<li *ngFor="let product of prod">
    <label>Name-{{product.name}}</label><br>
    <label>Cats: </label> <span *ngFor="let catItem of (cat | catFilterPipe: 'id' : product.cat)">{{catItem.name}},</span> 
</li>
</ul>

最后在您的模块中:

import { CatFilterPipe } from './cat-filter.pipe';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, HelloComponent, CatFilterPipe ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

答案 1 :(得分:0)

   prod.forEach((p:any) => { //for each element in prod
       //create a new property "catDesc"
       p.catDesc=p.cat.map(c=>cat.find(x=>x.id==c).name) //catDesc is an array
                      //get all elements of p.cat, and return the propertie
                      //name of the element of the list cat what has id equal to c
       })
      }