Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 695
Jonathan Wheeler Avatar asked Mar 02 '16 18:03

Jonathan Wheeler


People also ask

Can a JavaScript object key be a number?

Object Keys in JavaScriptEach key in your JavaScript object must be a string, symbol, or number.

Can a key be an object JavaScript?

The short answer is "no". All JavaScript object keys are strings. Even if you pass an object as a key, the object's toString() will be called on it, and the key will be stringified to [object Object] .

Do object keys have to be strings?

Restrictions in Naming Properties JavaScript object key names must adhere to some restrictions to be valid. Key names must either be strings or valid identifier or variable names (i.e. special characters such as - are not allowed in key names that are not strings).


1 Answers

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

like image 103
Matt Burland Avatar answered Oct 21 '22 21:10

Matt Burland