-1

I have a single object that returns the following:
{left: "642px", top: "305px", opacity: "1"}

I am trying to break these out into three separate variables: var left, var top, and var opacity

What is the simplest way to go about this?

Stephane Rolland
  • 38,876
  • 35
  • 121
  • 169
JCHASE11
  • 3,901
  • 19
  • 69
  • 132

6 Answers6

6

Use:

var data = {left: "642px", top: "305px", opacity: "1"};
var left = data.left,
    top = data.top,
    opacity = data.opacity;

DEMO: http://jsfiddle.net/dXxUc/1/

Ian
  • 50,146
  • 13
  • 101
  • 111
3
var left = object.left, top = object.top, opacity = object.opacity;

JavaScript doesn't have (currently) any fancy decomposing assignments like some other languages do.

Pointy
  • 405,095
  • 59
  • 585
  • 614
3

No shortcuts here:

var left = obj.left,
top = obj.top,
opacity = obj.opacity;
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
2

If this object is named myObject, you can retrieve the vars with :

var left = myObject.left;
Samuel Caillerie
  • 8,259
  • 1
  • 27
  • 33
0

It depends on how you intend to use them. If you are just going to save them into those variables once and there is one object then

var left = data.left;//or data["left"]
var top = data.top;//or data["top"]
var opacity = data.opacity;//or data["opacity"]
Travis J
  • 81,153
  • 41
  • 202
  • 273
0

If you are in the global scope, there is a shortcut to doing this:

for (p in o){
    if(o.hasOwnProperty(p)){
        window[p] = o[p];
    }
}

Note that this doesn't use var, but adds the properties to the window object. Properties of the window object are globally accessible directly in JS.

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139