如何在特定索引处替换列表中的元素
How to replace an element in a list at specific index
阅读 docs,他们说我可以在列表中添加一个元素,但我正在尝试并且它不断向文档添加一个新项目,键为 arrayName[index]
,如下所示:
我正在尝试这个查询:
await documentClient.transactWrite({
TransactItems: [{
Update: {
TableName: recordsTable,
Key: { id: selectedRec.id },
UpdateExpression: 'SET #k1 = :v1',
ExpressionAttributeNames: {
'#k1': `occurrences[${idx}]`, // idx = 245
},
ExpressionAttributeValues: {
':v1': selectedOccurrence, // a map object
},
}
}, {
// another query irrelevant to problem
}]
}).promise();
这就是本文档的结尾:
它应该替换 occurrences
数组中索引 245
中的对象,但它在我的文档中添加了一个带有键 occurrences[245]
的新地图。
我做错了什么?
您不能在 ExpressionAttributeNames
中包含下标。您只能指定属性名称。
有几种方法可以解决这个问题:
UpdateExpression: `SET #k1[${idx}] = :v1`,
ExpressionAttributeNames: { '#k1': 'occurrences' }
或:
UpdateExpression: `SET occurrences[${idx}] = :v1`
请注意,如果您的属性名称是 reserved word。
,则第二种解决方案将不起作用
阅读 docs,他们说我可以在列表中添加一个元素,但我正在尝试并且它不断向文档添加一个新项目,键为 arrayName[index]
,如下所示:
我正在尝试这个查询:
await documentClient.transactWrite({
TransactItems: [{
Update: {
TableName: recordsTable,
Key: { id: selectedRec.id },
UpdateExpression: 'SET #k1 = :v1',
ExpressionAttributeNames: {
'#k1': `occurrences[${idx}]`, // idx = 245
},
ExpressionAttributeValues: {
':v1': selectedOccurrence, // a map object
},
}
}, {
// another query irrelevant to problem
}]
}).promise();
这就是本文档的结尾:
它应该替换 occurrences
数组中索引 245
中的对象,但它在我的文档中添加了一个带有键 occurrences[245]
的新地图。
我做错了什么?
您不能在 ExpressionAttributeNames
中包含下标。您只能指定属性名称。
有几种方法可以解决这个问题:
UpdateExpression: `SET #k1[${idx}] = :v1`,
ExpressionAttributeNames: { '#k1': 'occurrences' }
或:
UpdateExpression: `SET occurrences[${idx}] = :v1`
请注意,如果您的属性名称是 reserved word。
,则第二种解决方案将不起作用