PHP
PHP

Reputation: 1

Map Object array values with other object value

Map cat ids of prod object with cat name string value from cat object. I want to display prod in HTML with string cat.

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>

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

Upvotes: 0

Views: 961

Answers (2)

Sreekumar P
Sreekumar P

Reputation: 6050

You can use Angular Pipe to filter the cats easily. And its angular way then.

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);

  }
}

Component 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

<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 { }

Upvotes: 0

Eliseo
Eliseo

Reputation: 58039

   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
       })
      }

Upvotes: 1

Related Questions