how to use reduce with query on Dynamodb scan

Viewed 102

I am learning DynamoDB and have difficulties understanding where to perform a reduction on data once a DynamoDB query has provided the results and where in the code it would go.

I would like to sum up the running_time_secs.

async function scanForResults () {
    try {
        var params = {
            TableName: "Movies",
            ProjectionExpression: "#yr, title, info.rating, info.running_time_secs, info.genres",
            FilterExpression: "#yr between :start_yr and :end_yr",
            ExpressionAttributeNames: {
                "#yr": "year",
            },
            ExpressionAttributeValues: {
                ":start_yr": 1950,
                ":end_yr": 1985,
            }
        };

        var result = await docClient.scan(params).promise()

        console.log(JSON.stringify(result))

        //const total = result.reduce((sum, result) => sum + result.info.running_time_secs, 0);

    } catch (error) {
        console.error(error);
    }
}

scanForResults();

Thanks for any help.

1 Answers

EDITED

Maybe you can post the actual value of the result once you resolve it. It would be best to know the actual structure of the result value to better see how you should approach it. You can site the documentation for further reference. It is actually really helpful.

var result = [{
  "title": "Piranha",
  "year": 1978,
  "info": {
    "rating": 5.8,
    "genres": ["Comedy", "Horror", "Sci-Fi"],
    "running_time_secs": 5640
  }
}]

var total = result.reduce((sum, result) => sum + result.info.running_time_secs, 0);

console.log(total);

var result2 = [{
    "title": "Piranha",
    "year": 1978,
    "info": {
      "rating": 5.8,
      "genres": ["Comedy", "Horror", "Sci-Fi"],
      "running_time_secs": 5640
    }
  },
  {
    "title": "Piranha2",
    "year": 1980,
    "info": {
      "rating": 5.8,
      "genres": ["Comedy", "Horror", "Sci-Fi"],
      "running_time_secs": 5640
    }
  }
]

var total2 = result2.reduce((sum, result) => sum + result.info.running_time_secs, 0);

console.log(total2);

var resultObj = {
  "title": "Piranha",
  "year": 1978,
  "info": {
    "rating": 5.8,
    "genres": ["Comedy", "Horror", "Sci-Fi"],
    "running_time_secs": 5640
  }
}

var totalObj = resultObj.reduce((sum, result) => sum + result.info.running_time_secs, 0);

console.log(totalObj);

I think base on the error you are receiving, result might not be an array. You can refer to the code snippet I posted. I used your code and just created the result array to mimic the result you get from the scan function. As you can see on the 3rd reduce function used on resultObj, I got the response error you got. reduce is an array method and using it to an object would result in such an error because object does not implement this method. Hence, I think that the result you are getting is not an array.

Related