[SalesForce] How to use a JavaScript object as an aura:attribute

How do I use a JavaScript object as an aura:attribute?

Should I do it this way
<aura:attribute name="jsObj" type="Object" default="{aValue: 5}"/> or another?

Best Answer

As Kris Gray (@GrayJustise) pointed out on Twitter once, Object is a simple Object, and Lightning doesn't know what to do with it, so it does this only safe thing it can: it makes it a String. Instead, use a Map, which tells Lightning that you have a key-value pair in there you're trying to parse:

<aura:attribute name="jsObj" type="Map" default="{'aValue': 5}"/>

Note that you should be using JSON-like syntax (e.g. quoting strings, etc). Lightning will try to do the right thing if you specify Map, but most likely will not if you specify Object. Note that this only applies to the default attribute. If you are setting the attribute inside of a method (via component.set), it doesn't matter which you use:

<aura:attribute name="jsObj" type="Object" />

init: function(component, event, helper) {
  component.set("v.jsObj", { aValue: 5 });
}