What is the best way to retrieve a complete DynamoDB scan response using aws-sdk-js-v3 without object types included in the marshaled response?

After struggling with the AWS JS SDK V3 documentation and examples, I decided to share my findings to help others. The official SDK docs were frustrating and misleading, especially when it came to showing marshaled output properly. While the DDB Doc client can remove object types from the response, they don't explain how to do it clearly. In my answer below, you'll find a solution for getting a clean, marshaled response.

Here's an example of an unmarshalled response, where you see S indicating string as the value type:

[
    {
      project_name: { S: 'fake project' },
      service_now_request_id: { S: 'CHG000212312' },
      service_now_request_url: {
        S: 'https://service-now.com/sampleApp?id=snx&spa=1&m=changes&r=0d12121aa442f33c8e0ebb3555'
      }
    }
]

If you'd like a cleaner response format like the one shown below, using the full DDB document client is recommended:

[
    {
        project_name: 'fake project',
        service_now_request_id: 'CHG000212312',
        service_now_request_url: 'https://service-now.com/sampleApp?id=snx&spa=1&m=changes&r=0d12121aa442f33c8e0ebb3555',
    }
]

Answer №1

Check out my code snippet below and feel free to provide feedback or offer an ES6 version:

const {DynamoDB} = require("@aws-sdk/client-dynamodb");
const { DynamoDBDocument } = require('@aws-sdk/lib-dynamodb');

const client = new DynamoDB({region: "us-west-2",});
const ddbDocClient = DynamoDBDocument.from(client);

async function fetchScanResults() {

    const tableName = "yourDDBTableName";

    scanParams = {TableName: tableName};

    try {
        let scanResult = await ddbDocClient.scan(scanParams);
        let output = [];
    
        do {
            scanResult.Items.forEach((item) => output.push(item));
            scanParams.ExclusiveStartKey = scanResult.LastEvaluatedKey;
        } while (typeof scanResult.LastEvaluatedKey != "undefined");
    
        console.log(output);
        // Sample result:
        // [
        //     {
        //       project_name: 'fake project',
        //       service_now_request_id: 'CHG000212312',
        //       service_now_request_url: 'https://service-now.com/sampleApp?id=snx&spa=1&m=changes&r=0d12121aa442f33c8e0ebb3555',
        //     }
        // ]
    }
    catch(error) {
        throw error;
    }
}

fetchScanResults();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtain the value stored in the session

How can I hide a form based on a specific session being set? Here is my approach: <form action="" method="post" <?php if ((isset($_SESSION['start']) )|| (isset($_SESSION['visitor']) )){ echo 'style="display:none;"'; } ? ...

Understanding Pass by Reference within Objects through Extend in Javascript with underscore.js Library

When working with Javascript and using the extend function in the underscore.js library, I am curious about what happens in relation to memory. Consider this example: var obj = {hello: [2]}; var obj2 = {hola: [4]}; _.extend(obj, obj2) obj2.hola = 5; conso ...

issue with animation occurs when the value changes while the setTimeout timer is still running

function wallpaperMediaPropertiesListener(event) { // reset animation test.stop(true); test.css('margin-left', 0); // set song title. test.text(event.title); var testWidth = test.outerWidth(); // clone text ...

What is the best method for including parameters in OBJECT_URL when sharing a post on Facebook?

Regarding this line: FB.api('/me/namespace:read' + '?article=http://www.xxxxxxxxxxxxxx/tm/redir.php&access_token=','post', Whenever I attempt: I encounter errors. How can I successfully pass parameters in the OBJECT_UR ...

Trigger the datepicker's onselect event programmatically

Does anyone know how to manually trigger the onselect event of a datepicker? My code is currently functioning correctly (retrieving data from a database based on the value of the datepicker's altfield), but I'm having an issue where the onselect ...

Stop automatic selection of the last value in ng-options using AngularJS

I'm facing an issue related to AngularJS. The problem I'm encountering is that... In my code, there are two select elements. Whenever I choose an option from the first select, an Ajax call is made using ng-change to populate the second select ba ...

Creating a cascading select box with two levels in PHP and MySQLExplanation on how to generate a two-tier connected

While I have successfully retrieved values from a MySQL database using a select box in PHP, I am struggling with implementing a two-level chained select box. Does anyone have any sample code or suggestions on how to achieve this? Thank you. ...

Button cannot be activated upon selecting a row

The goal is to activate a button when a row is selected. However, the button remains disabled even after selecting a row. Below is a snippet of the code as well as a screenshot showing the issue [error_1]: onInit: function () { var oViewMode ...

JSON.stringify alters the format of a date object

I have a website where users can log in with a specific timezone, regardless of the client-side timezone. When a user selects a date on the website, it is sent to the server side using JSON.stringify along with other properties. However, when the date is r ...

How can I trigger the execution of textarea HTML code with an onClick event using JavaScript?

When my fingers are lifted from the keyboard, some code will be automatically executed. I want to trigger this function when I click a button (onclick) instead of using onkeyup. <div id="result"></div> <textarea ...

Show JSON information from a jQuery post request

Greetings, I am currently working on implementing a login script using Ajax. My objective is to retrieve and display data such as email and username, and then store it in local storage. Although I can successfully obtain the data in JSON format, I want to ...

The v-for loop seems to be malfunctioning in my Nuxt 3 project

I have a script with mock data stored in a variable named whatsHappeningItems, and I am trying to pass this data as a reference to a card component using v-for="whatsHappening in whatsHappeningItems". However, when I do this, I encounter the following erro ...

What is a global variable used for in JavaScript?

Here is the code snippet that I am currently working on: $(".link").each(function() { group += 1; text += 1; var links = []; links[group] = []; links[group][text] = $(this).val(); } ...

When a Javascript function marked as async is executed, it will return an object

Async function is returning [object Promise] instead of the desired real value. Interestingly, I can see the value in the console log. It seems like this behavior is expected from the function, but I'm unsure how to fix my code. This code snippet is ...

Encountering a 500 Internal Server Error message while attempting to access a WebMethod through ajax

I'm encountering an issue with accessing my C# WebMethod in the code behind, resulting in a 500 internal server error. I cannot figure out why it's not working, so any assistance in identifying the problem would be highly appreciated. Even when ...

What is the process for implementing document.ondrop with Firefox?

I'm experiencing an issue where the document.ondrop function seems to be working in Chrome, but not in Firefox. Here's a link to an example demonstrating the problem: In the example, if you try to drop a file onto the page, it should trigger an ...

Experiencing a JSONP issue with an 'Access-Control-Allow-Origin' error

When working with PHP, I often use the following code to echo JSONP formatted data: echo $_GET['callback'] . '('.json_encode($arr).')'; In my AngularJS (JavaScript) code, I make a GET request like this: $http.get('http ...

Having difficulties executing a JavaScript file in the command prompt

I'm having trouble running a JavaScript file in the command prompt. Can anyone assist me with this issue? D:\>Node Welcome to Node.js v12.14.1. Type ".help" for more information. > 001.js undefined > Node 001.js Thrown: Node 001.js ...

How can I make the top two divs stay fixed as I scroll down, and then reset back to their initial position when scrolled

Hey there, I'm looking to have a div stay fixed after scrolling within its parent div. <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12"> <div class="fw ofndr-box"> <div class="ofndr-box-half add-here"> <a href="#! ...

The issue of why iterating over an array of objects does not function properly in React JS

P.S: I have made some modifications to the code below. Extracting the doctor's value from JSON data, updating the state, and then mapping it to print out the values. Initially, there is only one doctor, but in the future, there could be more than one ...