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?
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?
Use:
var data = {left: "642px", top: "305px", opacity: "1"};
var left = data.left,
top = data.top,
opacity = data.opacity;
var left = object.left, top = object.top, opacity = object.opacity;
JavaScript doesn't have (currently) any fancy decomposing assignments like some other languages do.
No shortcuts here:
var left = obj.left,
top = obj.top,
opacity = obj.opacity;
If this object is named myObject
, you can retrieve the vars with :
var left = myObject.left;
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"]
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.