如何在TypeScript中使用for循环提取DynamoDB roleGroups列表的Mapper数据
修正后可直接运行的代码
if ( newImage.roleGroups?.L?.length && // 校验所有列表项的M结构都存在,避免后续取值报错 newImage.roleGroups.L.every(item => item.M != null) ) { const roleGroupList = newImage.roleGroups.L; // 用for...of遍历数组,不要用for...in(for...in是遍历对象键的,不适用于数组) for (const roleGroupItem of roleGroupList) { // 取出单条roleGroup的M结构数据 const currentRoleGroup = roleGroupItem.M; const recordsToJoinEngagementsGroups: string[] = [ record.eventName, record.eventSourceARN.split('/')[1], '0', '1900/01/01 00:00:00', ]; // 所有roleGroup维度的属性都从当前遍历到的单条数据里取,不要从newImage根节点取 recordsToJoinEngagementsGroups.push( getAttributeValue(newImage.engagementId), getAttributeValue(currentRoleGroup.id), getAttributeValue(currentRoleGroup.parentGroupId), getAttributeValue(currentRoleGroup.name), getAttributeValue(currentRoleGroup.start), getAttributeValue(currentRoleGroup.end), getAttributeValue(currentRoleGroup.createdat, true), getAttributeValue(currentRoleGroup.updatedat, true), ); const latestUpdatedTime = Math.max( Number(currentRoleGroup.updatedAt.N), Number(currentRoleGroup.createdAt.N), ); recordsToJoinEngagementsGroups.push(decodeTimestamp(latestUpdatedTime)); dataStreamEngagementsGroups += recordsToJoinEngagementsGroups .join(separator) .replace(/(?:\r\n|\r|\n)/g, ' ') + '\n'; } }
核心修改说明
- 遍历逻辑调整:将原代码的
for...in替换为for...of遍历newImage.roleGroups.L数组,for...in是专门用于遍历对象键名的语法,用于数组会返回非预期的结果 - 取值路径修正:原代码所有角色组相关字段都从
newImage根节点取,实际DynamoDB返回的列表子项数据都存在单条元素的M属性下,需要先取出当前遍历项的M结构再取值 - 校验逻辑优化:原代码只校验了第一个列表项的
M结构存在,现在用every方法校验所有列表项的M结构都有效,避免运行时报错 - 注意字段大小写匹配:代码中
createdat/createdAt、updatedat/updatedAt的大小写要和DynamoDB中实际存储的字段名保持一致,避免取不到值
内容的提问来源于stack exchange,提问作者Umar Chaudhry
相关产品推荐
相关产品推荐

