[英]Find index of object in list in DynamoDB using Lambda
I am trying to use a Lambda script to find the index of an object in a list.我正在尝试使用 Lambda 脚本在列表中查找 object 的索引。 As an example, I would like to pass in
"userid": "041c9004"
and "author": "JK Rowling"
and return index=1
from the books
list.例如,我想传入
"userid": "041c9004"
和"author": "JK Rowling"
并从books
列表中返回index=1
。 If the object does not exist within the books
list, return index=-1
.如果 object 在
books
列表中不存在,则返回index=-1
。 We can assume that there will be no duplicate entries.我们可以假设不会有重复的条目。
The structure of the DynamoDB table looks like this. DynamoDB 表的结构如下所示。 Userid is the primary key.
Userid 是主键。
{
"books": [
{
"author": "J.R.R. Tolkien",
"title": "Lord of the Rings"
},
{
"author": "J.K Rowling",
"title": "Harry Potter"
},
{
"author": "George RR Martin",
"title": "A Song of Ice and Fire"
}
],
"isactive": true,
"ispublic": true,
"lastupdated": 1597690265,
"userid": "041c9004"
}
Here is what I have written of the Lambda function. It is returning index=-1
.这是我写的 Lambda function。它返回
index=-1
。
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({region: 'us-east-1'});
exports.handler = function(event, context, callback){
var params = {
TableName: 'Users',
Key: {
userid: event.userid
}
};
docClient.get(params, function(err, data){
if(err) {
callback(err,null);
} else {
callback(null, data);
//trying to populate this variable with the correct index
var indexOfAuthor = data.Item.books.indexOf(event.author);
console.log('The index of the author is ' + indexOfAuthor);
}
});
};
Assuming event.author
is just the author name, you could try:假设
event.author
只是作者姓名,您可以尝试:
data.Item.books.findIndex(i => i.author === event.author)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.