1

Have a look

console.log(docs);
console.log(docs.key);
console.log(docs.user);
// outputs:
[ { key: 'HunueVwerwbZwesZHxntesDciakecyiJ',
user: '[email protected]',
createdAt: Mon Mar 17 2014 08:48:30 GMT-0400 (EDT),
_id: 5326ef1ee883062522faa4a8,
__v: 0 } ]
undefined
undefined

What's wrong with the way I am trying to access this object?

2
  • You've wrapped it as an array. docs[0].key would work. Commented Mar 17, 2014 at 12:58
  • That's an array, the object is the [0] element. Commented Mar 17, 2014 at 12:59

1 Answer 1

3

docs is an Array. You can check that like this

console.log(Array.isArray(docs));
// true

So, you can check the length of the array, like this

console.log(docs.length);
// 1

Since it has only one element, we can access the first element with the subscript notation, like this

console.log(docs[0].key);
console.log(docs[0].user);

Note: We access the first element with 0, because JavaScript Arrays start with index 0.

Instead you can drop the object and retain only the array, like this

docs = docs[0];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.