javascript - 如何在javascript中找到比较两个值的第三个值?

这里我有两个数组array1和array2,我想从array1中找到哪个array1 的名字与array2值匹配,如何在javascript中找到id?

array1:


[ {id: 1, name:"Hindi"}


 {id: 2, name:"English"}


 {id: 3, name:"French"}


 {id: 4, name:"Russian"}


 {id: 5, name:"Urdu"}


 {id: 6, name:"Japanese"}


]



array2:


["Hindi","Russian","Urdu"]



我试过这个代码


console.log(array1.find(x => x.name === array2).id;



时间:

你可以使用 filter() 来获取名字在 array.然后对象使用 map() 将值数组转换为id数组 。

在你的代码中,你将字符串与数组 x.name === array2 进行比较。 你应该使用 includes()


let arr = [ {id: 1, name:"Hindi"}, {id: 2, name:"English"}, {id: 3, name:"French"}, {id: 4, name:"Russian"}, {id: 5, name:"Urdu"}, {id: 6, name:"Japanese"} ]


let lang = ["Hindi","Russian","Urdu"];



let res = arr.filter(x => lang.includes(x.name)).map(x => x.id);


console.log(res)

你应该将 filter 方法与 map 和析构结合使用


let arr1 = [ {id: 1, name:"Hindi"}, {id: 2, name:"English"}, {id: 3, name:"French"}, {id: 4, name:"Russian"}, {id: 5, name:"Urdu"}, {id: 6, name:"Japanese"} ], arr2 = ["Hindi","Russian","Urdu"];



console.log(arr1.filter(({name}) => arr2.includes(name)).map(({id}) => id));

我想你应该检查一下这个帖子看看它是否符合你的需要: 最简单的数组交集代码

编辑:对不起,我知道这应该是一个评论,但是,我还没有做到。

尝试这个:


 var a = [{


 id: 1,


 name:"Hindi"


 }, {


 id: 2,


 name:"English"


 }, {


 id: 3,


 name:"French"


 }, {


 id: 4,


 name:"Russian"


 }, {


 id: 5,


 name:"Urdu"


 }, {


 id: 6,


 name:"Japanese"


 }]


 var b = ["Hindi","Russian","Urdu"];


 var c = a.filter(function(i){


 return b.indexOf(i.name)>-1;


 });


 console.log(c);//New Array with filtered values
...