frc frc - 1 month ago 10
AngularJS Question

length of array in json string returns unexpected results in angular ng-repeat

I have the following json:

[
{
"id": 1,
"name": "Vojislav Kovacevic",
"street": "Sava Burica",
"city": "Belgrade",
"state": "Zemun",
"zip": "11080",
"country": "Serbia",
"giftwrap": null,
"products": "[
{\"count\":2,\"id\":1,\"price\":275,\"name\":\"Kayak\"},
{\"count\":1,\"id\":2,\"price\":48.95,\"name\":\"Lifejacket\"}
]"
},
{
"id": 2,
"name": "dzimi",
"street": "dzimi strit",
"city": "belgrade",
"state": "zemun",
"zip": "11000",
"country": "serbia",
"giftwrap": null,
"products": "[
{\"count\":5,\"id\":1,\"price\":275,\"name\":\"Kayak\"},
{\"count\":3,\"id\":2,\"price\":48.95,\"name\":\"Lifejacket\"},
{\"count\":4,\"id\":3,\"price\":19.5,\"name\":\"Soccer Ball\"}
]"
},
{
"id": 3,
"name": "mimi",
"street": "cincar janka 7",
"city": "novi sad",
"state": "novi sad",
"zip": "11000",
"country": "serbia",
"giftwrap": null,
"products": "[
{\"count\":2,\"id\":1,\"price\":275,\"name\":\"Kayak\"},
{\"count\":1,\"id\":2,\"price\":48.95,\"name\":\"Lifejacket\"}
]"
}
]


However when I loop thru it like so:

<tr ng-repeat="order in orders">
<td>{{ order.products.length }}</td>
</tr>


I get
100, 153, 100
as results (respectively), and I am expecting
2,3,2
because that is how many objects there are inside each
products
.

Answer

It's because products holds a string value and not an array, so you are getting the character length returned for the string values.

The products need to be in the format of:

{
    "id": 2,
    "name": "dzimi",
    "street": "dzimi strit",
    "city": "belgrade",
    "state": "zemun",
    "zip": "11000",
    "country": "serbia",
    "giftwrap": null,
    "products": [
            {"count":5,"id":1,"price":275,"name":"Kayak"},
            {"count":3,"id":2,"price":48.95,"name":"Lifejacket"},
            {"count":4,"id":3,"price":19.5,"name":"Soccer Ball"}
        ]
  }