-3

I have a js object as below.

var t = { x: 0, y: 'string', v: 10000 };

my present code is.

if (!t.x || !t.y) {
    throw "x and y required";
}

My problem is in my code x can have the value 0 but if in that case I do a !t.x then I get true.

How can I ensure that my data has x and y and also ensure that x can have the value 0.

jsfiddle: https://jsfiddle.net/3jo7vx4p/

Any help is sincerely appreciated.

Mohammad
  • 21,175
  • 15
  • 55
  • 84
Arnab
  • 2,324
  • 6
  • 36
  • 60

1 Answers1

2

The method your are looking for is:

hasOwnProperty

e.g:

if(!t.hasOwnProperty('x') || !t.hasOwnProperty('y')) {

}
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
  • Or the ridiculously over-complex: `Object.keys(t).indexOf('x') === -1` (for the sake of a full answer, really, I would absolutely *not* recommend this approach ever...) :) – David Thomas Jun 02 '16 at 12:23
  • But the question was : How can I ensure that my data has x and y and also ensure that x can have the value 0 ? With your code x and y could be undefined and will pass the test. I would check x and y to be a number too. – Jose Hermosilla Rodrigo Jun 02 '16 at 12:28
  • I need x and y to have proper values , they can not be null or undefined – Arnab Jun 02 '16 at 12:38
  • @Arnab - sounds like you'll need `Number.isNaN` - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN. `if(Number.isNaN(t.x) || Number.isNaN(t.y)) { throw new Error(...) }` – Adam Jenkins Jun 02 '16 at 12:57
  • @Adam thanx but y is string, is there something for string which will handle null and undefined – Arnab Jun 02 '16 at 14:56