Jonathan Wheeler
Jonathan Wheeler

Reputation: 2699

Can I have a JavaScript object key without a value

I am wanting to store TaskPaper-like tasks in a JavaScript object. Suppose I have a task like

- Post to StackOverflow @priority(2) @due(2016-05-03) @flagged

This would turn into

{"name":"Post to StackOverflow", "priority": 2, "due":"2016-05-03", "flagged":"value"}

Flagged doesn't need a value and all I can think of is to use true or null

I would like to later filter tasks using if key in object and having true/false values wouldn't work with my workflow.

What would the SO community recommend as best practices.

Upvotes: 13

Views: 27471

Answers (2)

cwallenpoole
cwallenpoole

Reputation: 82028

The JSON specification won't let you create a key in an object without some value, and there isn't a definition of "undefined" (you can see here that the keywords are null, true, and false). If you're looking for a simple flag value, then your alternate approach could be:

if(object.key) // this would mean that the object has "key" and it is set 
               // to a truthy value.

Your other alternative might be something like:

if(key in object && object[key]) // Verifies key exists and has truthy value

Now, that being said, in JavaScript, you can be a little more expressive. For example:

> var k;
undefined
> var o = {k:k}
undefined
> o
Object {k: undefined}
> console.log('k' in o)
true

Upvotes: 4

Matt Burland
Matt Burland

Reputation: 45135

If you do something like if (myobj.flagged), then if your value of flagged is true, the test passes. If the flagged property doesn't exist, then you get undefined which is falsy. So it works with flagged:true, flagged:false and even no flagged property. So use true, and omit the property altogether when it's not supposed to be there (so for...in would work in that case).

Upvotes: 8

Related Questions