简体   繁体   中英

Array of objects filter by another array values

I'm new in Angular and trying to use as a filter values of array, that is inside object, which is inside another array. Second file, that should be filtered, contains array of objects. for example:

export const PART: Parts [] = [
  {
    title: 'param1',
    data: 'some data', //required information to get
  },
  {
    title: 'param2',
    data: 'other data',
  },
  {
    title: 'param3',
    data: 'another data',
  }
]



export const PROD: Prod[] = [
  {
    id: 1,
    name: 'item1',
    title: ['param1', 'param3']
  },
  {
    id: 2,
    name: 'item2',
    title: ['param2', 'param3']
  }
]
    

expected result: item1 receive in it's description data: 'some data' and 'another data'. item2 receive in it's description data: 'other data' and 'another data'. I would use method *ngFor in template for both items.

I need to assign data from const PART to item of const PROD according title 'param1'. Unfortunately I can't find any code example, that would work in this scenario. Thank you in advance.

You can modify the PROD array to accommodate data object as below.

export const PROD: Prod[] = [
 {
  id: 1,
  name: 'item1',
  title: ['param1', 'param3'],
  data: [],
 },
 {
  id: 2,
  name: 'item2',
  title: ['param2', 'param3'],
  data: [],
 },
];

Use the below functions to assign data to the PROD array based on the param in the title. Loop through the array in onInit or your respective function to assign the data.

findPartWithParams(param) {
 return this.PART.find((e) => e.title === param);
}

ngOnInit() {
  this.PROD.forEach((prod) => {
    prod.title.forEach((t) => {
      prod.data.push(this.findPartWithParams(t).data);
    });
  });
}

I have attached a working StackBlitz fork for reference.

https://stackblitz.com/edit/angular-ivy-12bkcd

prod.map((x)=>{
    x.title.map((y)=>{
        part.map((z)=>{
            if(y == z.title && x.id == 1){
                x.data.push(z.data)
            }
            if(y == z.title && x.id == 2){
                x.data.push(z.data)
            }
        })
    })
})
change prod to this add data:[]
[
    {
      id: 1,
      name: 'item1',
      title: ['param1', 'param3'],
      data:[]
    },
    {
      id: 2,
      name: 'item2',
      title: ['param2', 'param3'],
      data:[]
    }
  ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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