如何找到比较JavaScript中两个值的第三个值?

时间:2019-05-02 07:11:40

标签: javascript

这里我有两个数组array1和array2,我想从array1中找到ID,其中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;

4 个答案:

答案 0 :(得分:1)

您可以使用filter()获取名称在数组中的对象,然后使用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)

答案 1 :(得分:1)

您应结合使用filtermap解构

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

答案 2 :(得分:0)

尝试一下:

 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

答案 3 :(得分:0)

这也将起作用:)

document.getElementById("import-products-form").insertAdjacentHTML('beforeend', input);