Search code examples
backbone.jscollectionsnestedmodelsmarionette

How to use get to set model attributes from a nested object


Can anyone help with this problem? I have nested data which I am trying to set in the initialize event of my Marionette/Backbone model. Here is an example:

{
    "items": [
        {
            "name": "Coke",
            "description": "Fizzy drink",
            "price": [
                {
                    "retail": 2.50,
                    "shop": 3.50
                }
             ],
        },
       ...

So, I can get at this data in the model's initialize funciton like this:

...
initialize: function() {
    this.name = this.get('name');
    this.description = this.get('description');
}

To get the price, I have tried, for instance:

this.price = this.get('price[0].shop');

... and many other variations.

My question is, how do I get the price out of this structure?

The price will end up in a standard template e.g. <%= price %>

many thanks


Solution

  • If you are getting name like this this.get('name') as you said, then to get shop, try below.

    this.price = this.get('price')[0].shop;