-3

How do I check if a key doesn't exist in javascript?

I have the below and I want to check if docs[3].created exists and has a value and if it does then add it to the thevalue variable.

With this, since docs[3].created doesn´t exits I get "Cannot read property 'created' of undefined" error.

var docs=[{ created: 2016-01-10, name: "Claes"},{ created: 2016-01-11, name: "Lisa"}];

var thevalue = docs[3].created;

I really need some help with this, thanks a lot!

Cody Gray
  • 230,875
  • 49
  • 477
  • 553
Claes Gustavsson
  • 5,189
  • 9
  • 48
  • 76

1 Answers1

0

docs is an array of objects. Each object has a created element. However, you try to get the created of the third item, while you only have two items, so possible valid indexes are 0 and 1. You could do something like this:

var docs=[{ created: 2016-01-10, name: "Claes"},{ created: 2016-01-11, name: "Lisa"}];

var thevalue = (docs.length > 3) ? docs[3].created : undefined;

This will result in undefined under the current settings and will get rid of the error. If your array had a third element, then this would store it into the variable.

Lajos Arpad
  • 53,986
  • 28
  • 88
  • 159