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.
CodePudding user response:
Modify the PROD type as below.
export interface PROD {
id: number;
name: string;
title: string[] | Array<string>;
data: Array<string>;
}
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: string): PART {
return this.PART.find((e: PART) => e.title === param);
}
ngOnInit() {
this.PROD.forEach((prod: Prod) => {
prod.title.forEach((t: string) => {
prod.data.push(this.findPartWithParams(t).data);
});
});
}
I have attached a working StackBlitz fork for reference.
https://stackblitz.com/edit/angular-ivy-12bkcd
CodePudding user response:
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:[]
}
]