javascript - 使用对象外的变量作为对象变量
问题描述
我有这个代码
for (var i = 0; i < lootbox.length; i++) {
const { type } = lootbox[i]
const query = type + "_lootbox.hunt";
await lb.findOneAndUpdate(
{ userID: message.author.id },
{ $inc: { query: 1 } }
);
}
代码将 读取query
为自己的变量而不是type + "_lootbox.hunt"
,有没有办法在 中使用该查询$inc
?因为我想使用循环自动化它
又名。动态对象键
解决方案
据我了解,您想要的是:在每次迭代query
中type + "_lootbox.hunt"
,例如page1_lootbox.hunt
. 而你想要得到的是{ $inc: { "page1_lootbox.hunt": 1 }}
. 如果是这样,一个简单的解决方案将是
{ $inc: { [query]: 1 } } // { $inc: { "page1_lootbox.hunt": 1 } }
如果您想要不同的东西,请告诉我。