0

I've a simple scenario where I return JSON with nested objects with a Rails backend. I'm having trouble accessing the attributes of the nested object.

Example JSON:

[{
  category_id: 2,
  id: 34,
  name: "red",
  category: {
    name: "color"
  }
},
{
  category_id: 2,
  id: 35,
  name: "blue",
  category: {
    name: "color"
  }
}]

Say I want to access category color for item with an id of 35, this works fine in the console:

collection = new App.Collections.Colors()
collection.fetch()
model = collection.get(35)
model.get('category').name

Within my eco templates, I get the error, "Cannot read property 'name' of undefined." However, my template still shows I can access the object with [object Object] if I only indicate

<%= model.get('category') %>

Any ideas? I'm sure I'm not understanding something fundamental.

UPDATED

I realized some category names were nil which was causing the error. The above code should be fine.

  • I'm just realizing not all my items have a name stored, which was throwing the undefined error. I should be more careful :) – Reza Parang Jul 04 '13 at 02:32

1 Answers1

2

It seems that your JSON is malformed.

As per JSON spec, you need to wrap the keys with quotation marks.

Try the following instead:

[{
  "category_id": 2,
  "id": 34,
  "name": "red",
  "category": {
    "name": "color"
  }
},
{
  "category_id": 2,
  "id": 35,
  "name": "blue",
  "category": {
    "name": "color"
  }
}]
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
John Dong
  • 21
  • 2
  • John, good catch, although it ended up that some of my category names were nil, which was throwing the error! – Reza Parang Jul 04 '13 at 02:33
  • 1
    Ah I see. Then you could have something such as `<% if (typeof model != 'undefined' && typeof model.get('category') != 'undefined' && typeof model.get('category').name != 'undefined' { %> <%= model.get('category').name %> <% } %>` to ensure that name is not nil – John Dong Jul 04 '13 at 02:40