Reputation: 97
I am new to typescript .please help me in doing this. I have an array as below.
let pets=[{id:"1",name:"animal"},{id:"2",name:"animal"}];
i want to loop through pets and get the names of animals from another array Category where
let category = [{id:"1",name:"Dog"},{id:"2",name:"Cats"},{id:"3",name:"Cows"},{id:"4",name:"Goat"}]
get output as below,
// expected output,
newpets=[{id:"1",name:"Dog"},{id:"2",name:"Cats"}]
Upvotes: 0
Views: 565
Reputation: 1370
There can be many ways to do it. One way
let pets=[{id:"1",name:"animal"},{id:"2",name:"animal"}];
let Category = [{id:"1",name:"Dog"},{id:"2",name:"Cats"},{id:"3",name:"Cows"},
{id:"4",name:"Goat"}];
var newpets = [];
pets.forEach(pet => {
let animalType = Category.find(cate => pet.id === cate.id );
newpets.push({id:pet.id, name: animalType.name});
})
console.log(newpets);
Upvotes: 0
Reputation: 12960
Try this out. I have used, Array map() and Array find() to achieve this.
let pets=[{id:"1",name:"animal"},{id:"2",name:"animal"}];
let category = [{id:"1",name:"Dog"},{id:"2",name:"Cats"},{id:"3",name:"Cows"},{id:"4",name:"Goat"}]
let newPets = pets.map(eachPet => {
return category.find(eachCat => eachPet.id === eachCat.id)
})
console.log(newPets)
Upvotes: 5