使用JavaScript遍历对比两个JSON对象字段并生成新对象的方法
实现思路
为了提升匹配效率,我们先将对象2的用户数据转换为以wpID为键的映射表,后续可以直接通过键名快速查找对应imageURL,无需每次遍历用户列表。之后深拷贝对象1避免修改原始数据,再遍历文章列表完成字段注入即可。
完整实现代码
// 入参:obj1为对象1,obj2为对象2 // 1. 构建wpID到imageURL的哈希映射 const wpIdToImageMap = Object.fromEntries( obj2.usersData.map(user => [user.wpID, user.imageURL]) ) // 2. 深拷贝原始对象1,生成新对象obj3,避免污染原数据 const obj3 = structuredClone(obj1) // 若运行环境不支持structuredClone,可替换为以下代码: // const obj3 = JSON.parse(JSON.stringify(obj1)) // 3. 遍历所有文章节点,匹配ID并注入imageURL obj3.data.posts.edges.forEach(edge => { // 若匹配规则为文章ID对应wpID,将下一行的authorId改为edge.node.id即可 const authorId = edge.node.author.node.id const matchedImage = wpIdToImageMap[authorId] if (matchedImage) { edge.node.author.node.imageURL = matchedImage } }) // obj3即为最终的合并结果 console.log(obj3)
内容的提问来源于stack exchange,提问作者Rahul
相关产品推荐
相关产品推荐

