JavaScript中如何按position键关联对象数组并输出匹配的剩余属性值
实现方案
核心思路
先将原始基础数组obj转换为以position为键的索引映射,避免多次循环遍历数组,提升匹配效率。之后分别遍历pdf_header、pdf_footer数组,直接从映射中取值即可。
完整实现代码
// 原始数据 var logo = "your_logo_path"; // 示例logo变量 var obj = [{ "position": "Bottom Left", text: "2" }, { "position": "Top Center", image: logo, width: 22 }, { "position": "Bottom Right", text: "1" }, { "position": "Top Left", text: "9" }]; var pdf_header = [{ "position": "Top Left" }, { "position": "Top Center" }, { "position": "Top Right" }]; var pdf_footer = [{ "position": "Bottom Left" }, { "position": "Bottom Center" }, { "position": "Bottom Right" }]; // 1. 构建position映射表,剔除position属性存值 const positionMap = new Map( obj.map(item => { const { position, ...rest } = item; return [position, rest]; }) ); // 2. 生成输出数组 const pdf_header_output = pdf_header.map(item => positionMap.get(item.position) || {}); const pdf_footer_output = pdf_footer.map(item => positionMap.get(item.position) || {}); // 打印验证结果 console.log(pdf_header_output); console.log(pdf_footer_output);
代码说明
- 利用对象解构语法
const { position, ...rest } = item快速剔除不需要的position属性,剩余属性直接作为映射值 Map结构的查找效率远高于每次遍历数组匹配,当数组数据量较大时优势更明显- 匹配不到对应
position时直接返回空对象{},完全符合需求的输出格式
内容的提问来源于stack exchange,提问作者Hello
相关产品推荐
相关产品推荐

