在PUG(Jade)中遍历对象数组并对比两个数组的技术需求
没问题,这个需求用JavaScript结合PUG完全能实现,我给你整理了一套清晰的实现方案,包括基础版本和优化版本,你可以按需选用:
基础实现方案
直接通过嵌套循环遍历两个数组,检查ID匹配后渲染对应内容,逻辑直观易懂:
- // 定义你的数据源数组 - 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 } ] - 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" } ] // 遍历每个用户 each userItem in user h3 来自用户 #{userItem.name} 的匹配结果 // 遍历当前用户的每一个heart ID each heartId in userItem.hearts // 在store数组中查找匹配的项 each storeItem in store - if (storeItem.author.hearts.includes(heartId)) .matched-item h4 匹配的Store对象详情 // 遍历并渲染store对象的所有键值对 each value, key in storeItem if typeof value === 'object' && value !== null p <strong>#{key}:</strong> // 嵌套对象递归渲染内部属性 each subValue, subKey in value p #{subKey}: #{subValue} else p <strong>#{key}:</strong> #{value}
代码关键点解释
- 利用PUG的
each语法实现数组遍历,这是模板中处理列表数据的核心方式 - 使用JavaScript原生的
Array.includes()方法快速检查ID是否存在,语法简洁高效 - 针对嵌套对象(比如
product、author)做了递归渲染,确保所有层级的属性都能展示出来 - 给匹配项添加了
.matched-item类,方便后续通过CSS美化样式
性能优化方案
如果后续store数组会扩展到很大的规模,基础版本的嵌套循环可能会影响性能。可以提前构建一个ID映射表,减少重复遍历:
- // 提前构建heart ID到store项的映射,避免重复遍历整个store数组 - const storeMap = new Map(); - store.forEach(item => { item.author.hearts.forEach(id => { if (!storeMap.has(id)) { storeMap.set(id, []); } storeMap.get(id).push(item); }); }); - // 定义数据源数组 - 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 } ] // 遍历用户和他们的heart ID each userItem in user h3 来自用户 #{userItem.name} 的匹配结果 each heartId in userItem.hearts - const matchedStores = storeMap.get(heartId) || []; if matchedStores.length > 0 each storeItem in matchedStores .matched-item h4 匹配的Store对象详情 each value, key in storeItem if typeof value === 'object' && value !== null p <strong>#{key}:</strong> each subValue, subKey in value p #{subKey}: #{subValue} else p <strong>#{key}:</strong> #{value}
这种方式只需要遍历store数组一次构建映射,之后每次查找都是O(1)的时间复杂度,数据量越大,性能提升越明显。
内容的提问来源于stack exchange,提问作者Said951
相关产品推荐
相关产品推荐

