tomaytotomato
tomaytotomato

Reputation: 4028

Iterating through Models Attributes in Backbone?

I have a model that requests a JSON file like below:

[
{
    "ModifiedOn": "2015-04-08 11:17:28.0",
    "BuildingCode": "AU1010A1",
    "BuildingName": "REGUS - BRISBANE",
    "ActionRequired": "A"
},
{
    "ModifiedOn": "2015-04-08 11:17:28.0",
    "BuildingCode": "BR1044A1",
    "BuildingName": "RIO SUL - RIO DE JANEIRO",
    "ActionRequired": "A"
}]

In the console I can see the attributes like so

enter image description here

However when I try and access the model attributes like so, I am getting undefined.

console.log(this.model.attributes.length);

I tried parsing to JSON but that failed.

Do I have to access each individual object in the attributes array my model has?

Upvotes: 0

Views: 334

Answers (3)

StateLess
StateLess

Reputation: 5402

You can use toJSON(), for in loop to iterate through model attributes

var attrs = this.model.toJSON();
for(key in attrs){
   console.log((key + " -> " + attrs[key]);)
}

Upvotes: 0

jmvtrinidad
jmvtrinidad

Reputation: 3658

You can use something like this one.

//for array[object{}, object{},...]
for(var i = 0; i <data.length;i++)
{
    foreach(var key in data[i])
    {
        //print out the attributes for data[i].
        console.log(key);
        //print out the attribute values.
        console.log(data[i][key]);
    }
}

[EDIT]

//for object{object{}, object{},...}
foreach(var childObject in data)
{
    foreach(var key in childObject)
    {
        //print out the attributes for childObject.
        console.log(key);
        //print out the attribute values.
        console.log(childObject[key]);
    }
}

Hope it helps.

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190907

Its an object so you can use Object.keys(this.model.attributes).

Upvotes: 1

Related Questions