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

2
  • 4
    How is this a "jQuery object"? Commented Apr 25, 2013 at 14:41
  • How are you using the variables later? Commented Apr 25, 2013 at 14:43

6 Answers 6

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/

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

1 Comment

+1 as readability and maintenance counts!
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.

1 Comment

This is probably the best approach, but it's better (from a readability perspective) if you use multiple lines.
3

No shortcuts here:

var left = obj.left,
top = obj.top,
opacity = obj.opacity;

Comments

2

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

var left = myObject.left;

Comments

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"]

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.