Node.js 使用Lambda在DynamoDB中查找列表中对象的索引

Node.js 使用Lambda在DynamoDB中查找列表中对象的索引,node.js,aws-lambda,amazon-dynamodb,Node.js,Aws Lambda,Amazon Dynamodb,我试图使用Lambda脚本在列表中查找对象的索引。例如,我想传入“userid”:“041c9004”和“author”:“J.K Rowling”,并从图书列表返回索引=1。如果对象不在书籍列表中,则返回索引=-1。我们可以假设不会有重复的条目 DynamoDB表的结构如下所示。Userid是主键 { "books": [ { "author": "J.R.R. Tolkien", "ti

我试图使用Lambda脚本在列表中查找对象的索引。例如,我想传入
“userid”:“041c9004”
“author”:“J.K Rowling”
,并从
图书
列表返回
索引=1
。如果对象不在
书籍
列表中,则返回
索引=-1
。我们可以假设不会有重复的条目

DynamoDB表的结构如下所示。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"
}
下面是我写的Lambda函数。它正在返回
索引=-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);
        }
    });
};


假设
event.author
只是作者姓名,您可以尝试:

data.Item.books.findIndex(i => i.author === event.author)