0

I am working with dynamoose and a query returns me the following output

  [ Document { cost: 100 },
  lastKey: undefined,
  count: 1,
  queriedCount: undefined,
  timesQueried: 1 ]

When I try to do typeof(output) , it returns Object

When I try to do Object.keys(output) , it returns [ '0', 'lastKey', 'count', 'queriedCount', 'timesQueried' ]

When I do Object.entries(output), it returns [ [ '0', Document { cost: 100 } ],[ 'lastKey', undefined ], [ 'count', 1 ], [ 'queriedCount', undefined ], [ 'timesQueried', 1 ] ]

For my use, I need to get an Object which looks like this {cost: 100} and currently I am using

JSON.parse(JSON.stringify(output))

which gives me

[ { cost: 100 } ]

I havent encountered an object without a key value pair (I'm self taught), so I do not know how to approach this problem. And the current method seems inefficient and kinda wrong. Please advice me how I can do it in a proper way

  • 1
    It's called an [array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Array_object). It only has one element (`{cost : 100}`), at index `0`, but has other properties. – D. Pardal Jul 06 '20 at 20:10
  • 1
    Did you try `output[0]` ? – Maarten Veerman Jul 06 '20 at 20:12
  • All of the answers here are correct. At least if you are doing a scan or query. It's an array and doing `output[0]` will get you that single object. As mentioned in the documentation: `The results array you receive back is a standard JavaScript array of objects. However, the array has some special properties with extra information about your _______ operation that you can access. This does not prevent the ability do running loops or accessing the objects within the array.`. If you have any recommendations for how to improve this language to make it more clear, please submit a PR or contact me. – Charlie Fish Jul 06 '20 at 20:58

1 Answers1

1
JSON.stringify(output) //=> "[ { cost: 100 } ]"

What that means is that you have an array (denoted by []) with one item, which is an object (denoted by {}) with a single key cost.

Use [0] to get the first item in an array, and then use .cost to get the cost property.

console.log(output[0].cost) //=> 100

The reason that you are seeing other keys on that array is that it looks like that dynamoose library is adding some additional properties to the array before returning it. It's doing the equivalent of:

// vanilla js, not typescript
const output = [ { cost: 100 } ]
output.count = 1
output.timesQueried = 1

This gives the array properties in addition to the content. The dynamoose library appears to use this method to encode metadata about your queries alongside the returned data.

The default JSON serialization strategy for arrays does not serialize custom array properties, only the array members.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337