1

I'm trying to set a variable:

latestPostId = posts[latestPost].post_id

But in one scenario, it is not defined yet. What is the best way to check?

I have tried these:

if (data.post_id !== undefined) {
if (data.post_id !== 'undefined') {
if (typeof data.post_id != 'undefined') {

But none seem to work. What is the best way to check if posts[latestPost].post_id is defined?

  • 1
    `if (posts && latestPost in posts && 'post_id' in posts[latestPost])` – adeneo May 06 '14 at 21:49
  • Check out this question and explanation - http://stackoverflow.com/questions/519145/how-can-i-check-whether-a-variable-is-defined-in-javascript – WillardSolutions May 06 '14 at 21:50
  • possible duplicate of [javascript test for existence of nested object key](http://stackoverflow.com/questions/2631001/javascript-test-for-existence-of-nested-object-key) – Felix Kling May 06 '14 at 22:58

4 Answers4

0

What is the best way to check if posts[latestPost].post_id is defined?

Does posts[latestPost].post_id !== undefined work?

I would probably do posts[latestPost] && posts[latestPost].post_id.

djechlin
  • 59,258
  • 35
  • 162
  • 290
0

You can do it in multiple ways (your last one is ok):

   if (typeof data.post_id != 'undefined')

Or simpler

   if (data.post_id)

BUT: This may generate an error, if data does not exist at all. So you should do:

   if (data && data.post_id)

For an object like: a.b.c.d.e.f, you should do:

   if (a && a.b && a.b.c && a.b.c.d && etc)
zozo
  • 8,230
  • 19
  • 79
  • 134
0

You could use a helper to avoid long if statements and improve re-usability, something like:

/**
 * @param {string} key
 * @param {object} obj
 */
function keyExists(key, obj) {
  var res = key.split('.').reduce(function(acc,x) {
    return acc[x];    
  },obj);
  return res != null || false;
}

And use it like so:

var obj = {a: {b: {c:'foo'}}};

console.log(keyExists('a.b.c', obj)); //=> true
console.log(keyExists('a.b.c.d', obj)); //=> false

if (keyExists('a.b.c', obj)) {
  // it exists
}
elclanrs
  • 92,861
  • 21
  • 134
  • 171
0

The in operator checks an object for a property.

'post_id' in posts[latestPost]`

Some people prefer hasOwnProperty. in traverses an object's prototype chain, while hasOwnProperty doesn't.

guest
  • 6,450
  • 30
  • 44
  • I should point out that you can define a property to hold the value known as `undefined`. JavaScript, yeah! – guest May 06 '14 at 22:16