Reputation: 389
I have three arrays with some data like below.
client = [{id: 1, name: client 1}, {id: 2, name: client 2}];
company = [{id: 1, name: company 1}, {id: 2, name: company 2}];
case = [{id: 1, client: 1, company: 2, name: case 1},
{id: 2, client: 1, company: 1, name: case 2}];
in my view I need to show it like
How can I achieve that? My basic requirement is need to replace the case array id with related array's names. I'm new to angular and I'm using angular 4. Thanks in advance.
Upvotes: 1
Views: 412
Reputation: 41437
use forech to along with find to create a new array.
clients = [{id: 1, name: 'client 1'}, {id: 2, name: 'client 2'}];
companies = [{id: 1, name: 'company 1'}, {id: 2, name: 'company 2'}];
case: any[] = [{id: 1, client: 1, company: 2, name: 'case 1'},
{id: 2, client: 1, company: 1, name:'case 2'}];
custom = [];
constructor(){
this.case.forEach((item) => {
let company = this.companies.find((c) => c.id === item.company)
let client = this.clients.find((c) => c.id === item.client)
this.custom.push({
id : item.id,
company: (company) ? company.name : null,
client: (client) ? client.name : null,
name: item.name
})
})
}
Upvotes: 1
Reputation:
Since your joining table is case
, iterate over it and create a new array out of it with reduce
:
const clients = [{id: 1, name: 'client 1'}, {id: 2, name: 'client 2'}];
const companies = [{id: 1, name: 'company 1'}, {id: 2, name: 'company 2'}];
const cases = [{id: 1, client: 1, company: 2, name: 'case 1'}, {id: 2, client: 1, company: 1, name: 'case 2'}];
const joined = cases.reduce((p ,n) => {
p.push({
client: clients.find(c => c.id === n.client).name,
company: companies.find(c => c.id === n.company).name,
case: n.name
});
return p;
}, []);
console.log(joined);
EDIT For the sake of it, you can even reduce the code with a spread :
const clients = [{id: 1, name: 'client 1'}, {id: 2, name: 'client 2'}];
const companies = [{id: 1, name: 'company 1'}, {id: 2, name: 'company 2'}];
const cases = [{id: 1, client: 1, company: 2, name: 'case 1'}, {id: 2, client: 1, company: 1, name: 'case 2'}];
const joined = cases.reduce((p ,n) => [...p, {
client: clients.find(c => c.id === n.client).name,
company: companies.find(c => c.id === n.company).name,
case: n.name
}], []);
console.log(joined);
Upvotes: 1