循环到比较两个PUG(Jade)的对象数组中



我正在Javascript中尝试使用PUG模板(如果可能的话(来比较两个数组,当我在ID中找到对应项时,显示一些特定的元素。

// First Array : I iterate over "hearts" object 
// Called in PUG : - const user
[
{
"hearts": [
"5e70c63a94b27b164c9b897f",
"5e723c75e4bfdf4f58c55e32"
],
"_id": "5e6bb1189978fd5afc98c57a",
"email": "catherine@catherine.com",
"name": "Catherine",
"photo": "0121b7fe-b2ae-4e75-979d-7dea1a432855.jpeg",
"__v": 0
},
{
"hearts": [
"5e723c75e4bfdf4f58c55e32"
],
"_id": "5e6bc41f5915e3d2980a5174",
"email": "marc@marc.com",
"name": "Marc",
"photo": "4caa7bfb-6408-4893-a78b-fa6e8e5b03e7.png",
"__v": 0
}
]
// Second array : I iterate over "author.hearts" object 
// Called in PUG : - const store
[{
"product": {
"categories": [
1,
2
]
},
"_id": "5e6bcc76c4022eae00e22af6",
"date": "2222-02-20T21:22:00.000Z",
"author": {
"hearts": [
"5e723c75e4bfdf4f58c55e32",
"5e70c63a94b27b164c9b897f"
],
"_id": "5e6bb1189978fd5afc98c57a",
"__v": 0
},
"created": "2020-03-13T18:09:58.086Z",
"id": "5e6bcc76c4022eae00e22af6"
}]

我想循环第一个数组,找到第一个ID(此处为5e70c63a94b27b164c9b897f(,循环第二个数组,看看这个ID是否存在于"author.hearts"对象中。如果没有,则继续使用第二个ID,如果存在,则显示找到该ID的对象的所有密钥(标签、照片、_ID、日期…(。

在我的示例中,我的数组中只有一个对象,但稍后还会有更多对象。非常感谢您的帮助

如果我理解正确,你可以做这样的事情。循环浏览所有用户,当您在author.hearts中找到他们的id时,停止循环并返回用户的_id所在的对象。

var resultFound = undefined;
try {
user.forEach((el) => {
const id = el._id;
const result = store.find(el => el.author.hearts.includes(id));   
if (result) {
resultFound = result;
throw resultFound;
}
});
} catch (e) {
if (e !== resultFound) {
throw e;
}
}

最新更新