简体   繁体   English

使用其他对象值映射对象数组值

[英]Map Object array values with other object value

Map cat ids of prod object with cat name string value from cat object. 使用来自cat对象的cat name字符串值映射prod对象的cat id。 I want to display prod in HTML with string cat. 我想在HTML中用字符串cat显示prod。

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: HTML:

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

Actual output: 实际产量:

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

Name-Bindi
cat-[2,4]

Expected output: 预期产量:

Name-Necklace
cat-gold,silver,platinum

Name-Bindi
cat-silver,copper

You can use Angular Pipe to filter the cats easily. 您可以使用Angular Pipe轻松过滤猫。 And its angular way then. 然后它的角度方式。

Working Demo 工作演示

cat-filter.pipe.ts 猫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);

  }
}

Component TS 组件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" }]


}

Component HTML 组件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>

Finally in your module: 最后在你的模块中:

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

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, HelloComponent, CatFilterPipe ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }
   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
       })
      }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM