如何遍历数组并获取与id对应的名称并将结果分配给另一个数组

时间:2019-04-22 06:44:59

标签: javascript typescript

我是打字稿新手。请帮助我。 我有一个如下数组。

let pets=[{id:"1",name:"animal"},{id:"2",name:"animal"}];

我想遍历宠物并从另一个数组Category中获得动物的名字

let category = [{id:"1",name:"Dog"},{id:"2",name:"Cats"},{id:"3",name:"Cows"},{id:"4",name:"Goat"}]

获取如下输出,

// expected output,
newpets=[{id:"1",name:"Dog"},{id:"2",name:"Cats"}]

2 个答案:

答案 0 :(得分:5)

尝试一下。我曾经用Array map()Array find()来达到这个目的。

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)

答案 1 :(得分:0)

可以有很多方法来做到这一点。一种方式

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