Having trouble iterating through a JSON response in an Ember template

Here is the content of my JSON array:

{
    "object": {
        "assignments": [
            {
                "assignmentId": 14706368,
                "sectionId": 0,
                "assignmentTitle": "file attachment A",
                "assignmentStartDate": "01/01/1900",
                "assignmentStartTime": "01:00AM",
                "assignmentDueDate": "01/01/2100",
                "assignmentDueTime": "01:00AM",
                "isMarathonChain": "No",
                "assignmentTimeLimit": 0,
                "assignmentTimeRemaining": "0",
                "marathonAssignmentStatus": "MARATHON_NOT_ASSOCIATED",
                "showAssignmentAttemptsAndPasswordDetails": false,
                "assignmentAttemptsTaken": 0,
                "assignmentAttemptsAllowed": "1",
                "showPasswordForm": false,
                "isStartAssignment": true,
                "isResumeAssignment": false,
                "isSubmitAssignment": false,
                "passwordRequired": false,
                "isConvertToGeniusEnabled": false,
                "draftNumber": 0,
                "studentExceptionExistsForDueDate": false,
                "isPastUploadDate": false,
                "showMarathonPrerequisiteInfo": false
            }
        ],
        "sections": [
            {
                "sectionId": 241409387,
                "courseId": 241409386,
                "sectionName": "Section01"
            }
        ],
        "courses": [
            {
                "courseId": 241409386,
                "courseName": "Tricon.Connect_01",
                "showDiscipline": false
            }
        ],
        "users": [
            {
                "userId": 1000321061,
                "firstName": "Ragu &^&",
                "lastName": "+#@)()Tricon ^^",
                "userType": "S"
            }
        ],
        "returnLMS": [
            {
                "returnUrl": "bb"
            }
        ]
    }
}

I am attempting to loop through the assignment values in my template using the following code snippet:

{{#each obj in model.object}}
                <tr>
                {{#each assign in obj.assignments }}
                  <td>
                    {{assign.assignmentId} <br />{{assign.assignmentTitle}
                  </td>
                  {{/each}}
                </tr>
              {{/each}}

However, my loop is failing at the first line and I am not getting the desired output. I need these values to match certain conditions and display information.

Answer №1

To simplify the process, I now utilize the {{each-in}} helper within the template. For further information, you can refer to the details provided here. Below is an example tailored to suit your requirements:

{{#each-in model.object as |key values|}}
  <tr>
    {{#each values as |assign|}}
      <td>
        {{assign.assignmentId} <br /> {{assign.assignmentTitle}
      </td>
    {{/each}}
  </tr>
{{/each}}

If your intention is solely to iterate through assignments, indicated by assignment-specific code in the inner each loop, then the code would look like this:

{{#each model.object.assignments as |values|}}
  <tr>
    {{#each values as |assign|}}
      <td>
        {{assign.assignmentId} <br /> {{assign.assignmentTitle}
      </td>
    {{/each}}
  </tr>
{{/each}}

Alternatively, if you wish to cycle through different keys and apply varying templates based on the current key, consider implementing the following approach:

{{#each-in model.object as |key values|}}
  {{#if (eq key 'assignments')}}
    <tr>
      {{#each values as |assign|}}
        <td>
          {{assign.assignmentId} <br /> {{assign.assignmentTitle}
        </td>
      {{/each}}
    </tr>
  {{/if}}
  {{#if (eq key 'sections')}}
    <tr>
      {{#each values as |section|}}
        <td>
          {{section.sectionId} <br /> {{section.sectionName}
        </td>
      {{/each}}
    </tr>
  {{/if}}
{{/each}}

Ultimately, the decision lies with you and the objectives of your application 😂 Additionally, note that the example incorporates the use of ember-truth-helpers for functionalities like the {{#if}} conditions mentioned above.

Answer №2

After reviewing the JSON example provided, it appears that the issue lies within the following code snippet:

{{#each obj in model.object}}

The problem stems from the fact that model.object is recognized as a Javascript object rather than an array. The each loop functions specifically for arrays (and potentially array-like objects), not general Javascript objects. Should you wish to iterate through both keys and values of an object, a computed property must be established to accomplish this task.

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

XState: linking together multiple promises seamlessly without needing intermediate states

After reading the Invoking Multiple Services section, it seems that despite being able to invoke multiple promises, they appear to be triggered without waiting for the previous one to complete in my own tests. // ... invoke: [ { id: 'service1' ...

What is the process of integrating hegel.js with a React application created using create-react-app?

Have you heard of Hegel.js? It's a powerful type checker that I recently discovered. Surprisingly, there isn't much information online about using hegel.js with React. Check it out at ...

Transform a 2-dimensional array of numbers into an array of objects labeled with a "row" index

Today my brain seems to be in full-on "fart" mode. Struggling to find a clean solution for this task without resorting to an ugly loop or recursion. I have a 2D array of numbers that looks like this: const layoutMatrix = [ 1, [1], [0.5, 0.5], [0.2 ...

Difficulty with Angular's Interpolation and incorporating elements

I've encountered an issue with String Interpolation while following an Angular course. In my server.component.ts file, I've implemented the same code as shown by the teacher in the course: import { Component } from "@angular/core"; @Component ( ...

"Error encountered when trying to send form data to PHP server via ajax due to an unauthorized

I'm encountering an issue whenever I run my code and it keeps showing this error: Uncaught TypeError: Illegal invocation Any ideas on how to resolve this? const formdata = new FormData(); for (const file of myfile.files) { formdata.append("myF ...

Tips for effectively making REST requests from a ReactJS + Redux application?

I'm currently working on a project using ReactJS and Redux, incorporating Express and Webpack as well. I have successfully set up an API and now need to figure out how to perform CRUD operations (GET, POST, PUT, DELETE) from the client-side. Could so ...

I want to import JSON information from a file to display on my website

I am trying to implement a JSON array on my webpage when a button or image is clicked. Here is the array I have: var products = [ { "productID":"1", "name":"Stark Navy", "url": "stark.jpg", "description": "Waterproof, double velcro straps", "price": " ...

Unable to utilize jQuery library in AngularJS partial HTML files, despite being loaded in the index.html file

I have been working with a web template that utilizes jQuery image gallery and other elements. Now, I am looking to convert this template into an AngularJS structure. To do so, I have created partial HTML pages like slider.html or contact.html along with t ...

Extract an array object from a JSON Object in C# using Json

Recently, I encountered a JSON string that was passed to my web API. string jsonstring = "{\"datamodel\": \"[{\"K1\":\"V1\",\"K2\":\"V2\"}]\"}"; Inside this JSON string, there can be multiple p ...

Upcoming Authentication Update: Enhancing User Profile with Additional Data Points

I recently encountered an issue with my typescript application that uses Next Auth v4 along with GithubProvider and MongoDBAdapter. I needed to add a new field called role to the User schema. Researching online, most solutions suggested adding a function ...

The MUI multiple select feature is experiencing issues following the addition of a new button

I'm having trouble adding buttons below a select dropdown menu with a specific height. When I try to put the menu item inside a div, the multiple select stops working and I have no idea why. Can someone help me figure this out? Check out my CodeSandb ...

Is it valid JSON to have values such as "ok", false, true, null, and 123?

Can the following strings be considered valid JSON? "ok" false true null 123 If not, why does the standard JavaScript JSON.parse method allow these values to be used as valid JSON? I have encountered issues when using these values in JSON REST APIs, ...

What could be the issue with my interactive dropdown menu?

I am currently experiencing an issue with a drop down list that is supposed to fetch records from a column in another table, but no records are appearing. Additionally, I would like to add an option in the drop down list labeled "others" for users to inp ...

A guide on leveraging console.log in Next.js

I'm having trouble displaying the output of an API call using console.log. The issue is that nothing appears in the console (both in the browser and Visual Studio Code). The only console.log that seems to work is within the RouteStatus function, but i ...

Numerous query parameters sharing identical names

I am seeking information on how EXPRESS handles multiple query parameters with the same name. Despite my research efforts, I have been unable to find a reliable source on this topic. Specifically, I am interested in how EXPRESS would interpret a URL such ...

Connecting Vue.JS page to my existing HTML page: A step-by-step guide

While developing my website, I faced a challenge with the structure. The home page was built using traditional HTML/CSS, while the other pages were created in Vue.js. Is there a method to connect these two different types of files? For instance, can I inc ...

Utilizing Angular to apply multiple ng-repeat directives with multiple filters

I am working on a project that involves multiple ng-repeat lists with several filters. Currently, I am using (ex:A.value) if (ex:B.value), but I would like to implement multiple filters. The filters I want to incorporate are recommend_search, skill_searc ...

Unexpected Behavior Arises from Axios Get API Request

Below is a functional example in my CodePen showing what should be happening. Everything is working as intended with hard coded data. CodePen: https://codepen.io/anon/pen/XxNORW?editors=0001 Hard coded data: info:[ { "id": 1, "title": "Title one ...

Error: Unspecified process.env property when using dotenv and node.js

I'm encountering an issue with the dotenv package. Here's the structure of my application folder: |_app_folder |_app.js |_password.env |_package.json Even though I have installed dotenv, the process.env variables are always u ...

Guide on sending an AJAX request to a server

I'm currently working on implementing AJAX and have encountered a roadblock. Specifically, I need assistance with sending a request to the server when a user clicks on a specific image, expecting the server to return that image. While I know how the s ...