Angular ng-repeat is producing unexpected results when determining the array length from a JSON string

Here is an example of JSON data:

[
    {
        "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\"}
        ]"
    }
]

When looping through this data with the following code:

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

The output is 100, 153, 100, but it should be 2, 3, 2 since each object contains a certain number of items in the products array.

Answer №1

The reason for this is that the variable "products" contains a string value rather than an array, which is why you are receiving the character length of the string values.

To rectify this, the products should be structured as follows:

{
    "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"}
        ]
  }

Answer №2

It seems like you are attempting to find the length of an array, but because the value of product is in quotes (indicating it's a string), the length property will only count the number of characters in the string.

If you're looking to get the number of items within the products array, consider removing the quotation marks around the array and leaving the rest of your code unchanged. Hopefully, this advice proves useful!

Answer №3

You have two options: modify the API response or convert the string into JSON format

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

Answer №4

The variable products contains string values, and you are retrieving the length of these strings. It seems like there may be an encoding problem originating from your backend system.

You might want to consider using

JSON.parse(order.products).length

It's important to note that this workaround does not address the root cause of the issue (which lies in the backend). For a complete resolution, it would be helpful to examine the backend code directly. You may also want to consider posing a separate question specifically addressing this particular aspect, such as: "When I encode my JSON data like this, I receive that on my client side instead of that2."

Answer №5

To ensure correct data processing, consider utilizing JSON.parse() on each products value:

    // .............
    // .............
    "country": "Serbia",
    "giftwrap": null,
    "products": JSON.parse("[
        {\"count\":3,\"id\":5,\"price\":189,\"name\":\"Canoe\"},
        {\"count\":4,\"id\":8,\"price\":32.50,\"name\":\"Paddle\"}
    ]")
},
{
    // ............

View the functioning jsfiddle here: https://jsfiddle.net/newexampleuser/abc123def456/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for submitting a form with multiple fields that share the same name attribute using ajax:

I have created an HTML form <html> <head></head> <form> <input type="text" name="question[]" /> <input type="text" name="question[]" /> <input type="file" name="image" /> <input type="submit ...

Storing Firebase Auth User references in a Firestore document: Tips and Tricks

I have developed an application that allows users to register and login, using Firebase Auth for authentication. In addition to Firebase Auth, I also utilize Firestore to manage multiple collections like "Requests" and "Offers". A user authenticated with ...

Detect mouse events using electron even when the window is not in focus

Is there a way to detect mouse events such as hover and click even when the Electron window is not the active focus? I want to ensure that my buttons' hover and click effects still function properly. Currently, I find that I have to switch back to th ...

Counting checkboxes in jQuery version 1.9

I recently upgraded my website from jQuery 1.6 to jQuery 1.9.1, and now some of my old code is not working as expected. Specifically, I have a piece of code that handles checkboxes in table rows, allowing only up to 5 checkboxes to be active at once and di ...

What are the best practices for managing promises effectively?

Currently, in my Angular application, I am utilizing $odataresource for handling data retrieval and updates. The code snippet I am working with is as follows: var measure = $odataresource("http://windows-10:8888/ChangeMeasure/"); var myMeasure = measure ...

Exploring JSON parsing with minimal-json and Gson libraries

When working on my Java program, I encountered an issue while trying to extract a specific key-value pair from a JSON response. The particular key I need is "first_aired_iso," which provides the air date for each TV show episode. To retrieve this informat ...

How to Deactivate Navigation Tabs in AnythingSlider?

I am encountering some issues with the css and js while using the AnythingSlider tool. Specifically, I want to modify the navigation tabs in a way that certain tabs will either remain unchanged or become inactive based on a ColdFusion conditional. For ins ...

Utilize the onClick event to access a method from a parent component in React

Looking for guidance on accessing a parent component's method in React using a child component? While props can achieve this, I'm exploring the option of triggering it with an onClick event, which seems to be causing issues. Here's a simple ...

Retrieving an array of objects through an Angular service

I'm fairly new to Angular and Javascript. Recently, I created an Angular service that fetches an array of users from an HTTP call returning JSON data. While the HTTP call is successful and returns the correct data, I'm having trouble passing this ...

What is the best way to create an answer label box that validates your response?

I am looking to design a question box label that resembles a search box. In this unique setup, users will have the option to input their answer into the question label. For example, if the user types 'kfuffle' as the answer, they will automatical ...

Use jQuery's $.post method to validate the form field and prevent submission if there are any errors

I am trying to validate a form field on submit and block the submission if an ajax response message is returned. Below is the JS code I have: $('form.p_form').submit(function (){ var description = $.trim($('#f9').val()); var aa = $.pos ...

Encountering a malfunction in executing the AngularJS controller file

In the project run with http-server and node.js, the angular controller is unable to connect with index.html. classifieds.js (function() { "use strict"; angular .module("ngClassifieds") .controller("ClassifiedsCtrl", ['$scope', ...

How can we merge all the values of keys within an object into a new array using ES6?

My objective is to transform dynamic data into an array based on the keys of the toolset object, which does not have a constant number of keys. { toolset:{ info1:{ event-date:{}, event-time:{}, }, info ...

Problematic situation when using ng-repeat with dynamic ng-include and template variables scope conflict

When utilizing ng-repeat with dynamic ng-include that includes variables, the variables are not being properly recognized. Take a look at this code snippet. Here is the main HTML code: <table style> <tr> <th>Student</th> ...

Steps for collapsing a column containing nested JSON objects within a dataframe that is already flattened

I'm dealing with a json file that contains nested objects which have been flattened into a pandas dataframe. One column in the dataframe holds these nested json objects and I'm struggling to flatten it. Although I've tried various methods, ...

Error arises during JSON parsing if the data content contains the `%` symbol

I'm struggling to solve an issue on my website related to a function that downloads articles dynamically. The problem arises when the article contains a % sign, causing a parse error. Can anyone assist me in modifying this function to handle the % sig ...

What is preventing the installation of this Chrome extension?

I am struggling to install a few short and simple extensions on Chrome. The error message I receive about the 'manifest version' indicates that the issue might be due to outdated information. Since I lack experience in Chrome extensions and JavaS ...

Show the chosen option when the textarea is no longer in focus

My form includes a text box and a button: <p><textarea rows="4" cols="30">Aliquam erat volutpat.</textarea></p> <p><input type="button" value="Submit"></p> When the user selects text in the textarea and then cl ...

Utilizing Dropwizard for hosting static HTML files

I'm in the process of developing an application using dropwizard and angularjs. I have configured my AssetsBundle as follows: bootstrap.addBundle(new AssetsBundle("/assets", "/", "index.html")); The challenge I am facing is that I want multiple page ...

API testing tool encounters a glitch with RESTful POST operations

When making REST calls (POST, GET) to my Scala Akka Application, I am using the POSTMAN app. Interestingly, the call works when made from angularJS, but I encounter an error when firing it from POSTMAN: The error message states: There was a problem with t ...