如何在Javascript中比较数组和对象?

Jan*_*ne 1 javascript arrays compare object

我有两个json数组和对象我想比较两个json并推送另一个对象

obj1 = ["user1", "user2"]
obj2 = [
  {
    "userName": "user1", 
    "id": "14" 
  },
  {
    "userName": "user2",
    "id": "9",
  },
  {
    "userName": "user3",
    "id": "3",
  },
  {
    "userName": "user4",
    "id": "1",
  }
]
Run Code Online (Sandbox Code Playgroud)

我想得到如下结果

[
  {
    "userName": "user1",
    "id": "14"
  },
  {
    "userName": "user2",
    "id": "9",
  }
]
Run Code Online (Sandbox Code Playgroud)

之后,我尝试比较两个数组并获得我需要的结果.

var obj1 = ["user1","user2"]
var obj2 = [
  {
    "userName": "user1",
    "id": "14"
  },
  {
    "userName": "user2",
    "id": "9",
  },
  {
    "userName": "user3",
    "id": "3",
  },
  {
    "userName": "user4",
    "id": "1",
  }
]

var objArray = [];
for (var i = 0; i < obj.length; i++) {
if (obj1[i] === obj2.userName) {
  objArray.push(obj2[i]);
}
return objArray;
Run Code Online (Sandbox Code Playgroud)

请帮我解决这个问题.提前致谢

Nin*_*olz 5

您可以通过检查名称来过滤Array#includes.

var array1 = ["user1", "user2"],
    array2 = [{ userName: "user1", id: "14" }, { userName: "user2", id: "9", }, { userName: "user3", id: "3", }, { userName: "user4", id: "1", }],
    result = array2.filter(({ userName }) => array1.includes(userName));
  
console.log(result);
Run Code Online (Sandbox Code Playgroud)