0

Here are the two lines:

pixels[x-left] = {};
pixels[x-left][y] = true;

It would greatly allow me to clean up some code if the two could be combined into a single expression.

My first attempt looked something like this:

pixels[x-left] = { y: true };

However the letter y is being used as the index instead of the value of y, which is not OK.

Joncom
  • 1,985
  • 1
  • 18
  • 29
  • @Abbas `y` is a variable. – Fabrício Matté Apr 15 '13 at 00:12
  • 1
    This is an often asked question. Duplicate with the most upvotes I could find: [Using a variable for a Javascript object key](http://stackoverflow.com/questions/2274242/using-a-variable-for-a-javascript-object-key) – Bergi Apr 15 '13 at 00:22

2 Answers2

3

I'll start right off saying that Bergi's solution should be preferred, but in case you don't mind killing your code's readability:

(pixels[x-left] = {})[y] = true;

Fiddle

This works as an assignment expression returns the assigned value (in this case, a reference to the assigned object).

Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166
2

No, there is not no clean one*. Any property name in an object literal is interpreted literally.

One way out would be some kind of helper function, like

Object.set = function(o, p, v) { o[p] = v; return o; };

pixels[x-left] = Object.set({}, y, true);

but then everybody reading your code would need to know about Object.set.

* After @Fabricio's answer I can't state "no possibility" any more :-)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375