10

How do I set a default value for an attribute with type Object? In the example below, the default value for the country attribute should be an object with two properties: name and capital. At runtime, however, it defaults to the string "{'name':'France','capital':'Paris'}" and not an object.

<aura:attribute name="country" type="Object" default="{'name':'France','capital':'Paris'}" />

My work-around for now is to set the value in the init handler, but I'd still like to know what I'm doing wrong.

15

Well using type="Map" works fine, and it returns object as expected.

<aura:attribute name="country" type="Map" default="{'name':'France','capital':'Paris'}" />

Here's the link to the section in the doc where attributes of collection type is discussed.

  • Yep, changing the type to Map works. I don't understand having a separate type of Map since in JavaScript an object is a map. At the very least the default syntax for map should also work for object. – Joe B Dec 7 '16 at 20:41
  • 2
    This topic got bumped a year later... I think it merits mention, though, that the type names in Lightning are based on Apex conventions not JavaScript. In Apex, Object means the most general class from which all other objects inherit. So when you set type="Object" you're not being specific enough, and it may interpret as a string. When you set type="Map" it explicitly knows to look for key-value pairs. – Charles T Oct 31 '17 at 4:50
  • 1
    Here's the supporting documentation where Salesforce recommends using the Map type instead of object: developer.salesforce.com/docs/atlas.en-us.lightning.meta/… – Charles Naccio Dec 15 '17 at 15:55
0

Accepted answer is the correct one but as an alternative approach, you can set the object in a helper function which can be initialized by an init method when the component is created. For example:

cmp.set('v.country', {
  name: 'France',
  capital: 'Paris,
});

I like this approach because if there are many objects on the HTML, lot of code can be moved and HTML is cleaner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.