-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.

2

1 Answer 1

2

The method your are looking for is:

hasOwnProperty

e.g:

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

}
Sign up to request clarification or add additional context in comments.

5 Comments

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...) :)
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.
I need x and y to have proper values , they can not be null or undefined
@Arnab - sounds like you'll need Number.isNaN - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. if(Number.isNaN(t.x) || Number.isNaN(t.y)) { throw new Error(...) }
@Adam thanx but y is string, is there something for string which will handle null and undefined

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.