Angular encountered an issue while attempting to differentiate '[object Object]'. The permissible types for differentiation are limited to arrays and iterables

I need help iterating through an Object received from a service call and displaying it in a table using *ngFor.

Unfortunately, I encounter the following error during this process:

Error trying to diff '[object Object]'. Only arrays and iterables are allowed

I am aware that you cannot iterate through an Object directly, but I couldn't find a solution that made sense to me. Please take a look at my code below and any assistance would be highly appreciated :

.ts

searchValue: string = "3";
logList: any = [];
   
getLogs() {
        const numOfLogs = new FormData();
        numOfLogs.append('n_log', this.searchValue)
        this.fileUploadService.getLogs(numOfLogs).subscribe(
          data =>  {this.logList = data},
        );
      }

html

<table class="table table-striped" style="width:1000px;table-layout:fixed;font-size:10px;color:black;">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Date</th>
                        <th>FilePath</th>
                        <th>Updated</th>
                    </tr>
                </thead>
                <tbody>
                    <tr *ngFor="let item of logList">
                        <td>{{ item.Name}}</td>
                        <td>{{ item.Date}}</td>
                        <td>{{ item.FilePath}}</td>
                        <td>{{ item.Updated}}</td>
                    </tr>
                </tbody>
            </table>

console.log(this.logList)

{
  "Name": [
    "name1",
    "name2",
    "name3"
  ],
  "Date": [
    "2021-12-13",
    "2021-12-12",
    "2021-12-11"
  ],
  "FilePath": [
    "FileName1.xlsx",
    "FileName2.xlsx",
    "FileName3.xlsx",
  ],
  "Updated": [
    "2021-12-31T00:00:00",
    "2021-12-31T00:00:00",
    "2021-12-31T00:00:00",
  ],
}

Answer №1

Try using the keyValue pipe instead since loglist is not an array. The following code snippet should help resolve your issue:

            <tbody>
                <tr>
                    <td *ngFor="let item of logList | keyvalue"">{{ item.value}}</td>
                </tr>
            </tbody>

Answer №2

*ngFor does not support iterating over Objects. Should it iterate through the keys of the object, or the values?

If you were to execute the following code:

this.fileUploadService.getLogs(numOfLogs).subscribe(
    data => { console.log(typeof data); this.logList = data; }
);

It would display 'object' in the console.

To iterate through an object in the template, you can either convert it into an array or iterable in the .ts file and use that instead:

let iterableLogList = Object.keys(this.logList);

Alternatively, you can utilize Angular's built-in keyvalue pipe on this.logList.

*ngFor="let item of logList | keyvalue"

No additional imports will be required for this approach. Now, each item's key will be accessible in the template as item.key, and similarly the value will be available as item.value.

Answer №3

After trying multiple solutions without success, I eventually realized that the issue was caused by an empty array in my scenario. The error stemmed from me attempting to check values before they were assigned due to an asynchronous http service call. All it took to fix the problem was adding a simple conditional statement:

            <div *ngIf="logList">
                <span *ngFor="let item of logList">

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

What is the process for programmatically importing a module into the local scope in Node.js?

The coding environment is using a browser and the bundle tool being used is webpack. In my router.js file, I have the following code: import foo from './views/foo.vue' import bar from './views/bar.vue' import zoo from './views/zoo. ...

Developing a Voting System in CodeIgniter

Currently, I am working on implementing a voting system in my CodeIgniter project called "like". I came across a method on and followed it. After successfully updating the database, I faced an issue where the like count was not displaying on the view. In ...

The TypeScript 'object' type

My query regarding the definition of TypeScript's {} type has brought about some confusion. Initially, I believed it represented an "empty object with no properties," but I recently encountered an ESLint rule that prohibits the use of {} type because ...

Navigating to a child route from a parent component in Angular using the navigate method: A step-by-step guide

Here is the code snippet for my HTML routerLink: <a [routerLink]="['create']">Create</a> - it's working just fine. When I try to call the same on a button click, it doesn't work.. navigateTo(page) { this.router.na ...

SVG.js created a surprising polyline in the svgdom node

My svg.js code generates different SVG strings in the browser (correct) and at node (incorrect with excessive inner SVG elements). Here is my code for the browser: let size = { width: 512, height: 512 }; let entity = { x: 232, y: 162, rx: 137, r ...

What is stopping me from utilizing ES6 template literals with the .css() method in my code?

I am currently working on a project where I need to dynamically create grid blocks and change the color of each block. I have been using jQuery and ES6 for this task, but I am facing an issue with dynamically changing the colors. Below is the snippet of m ...

Divergent find function behavior in jQuery when applied to div or tbody

I've encountered an issue while using the jQuery find selector by Id with a div and tbody. Let me simplify my problem for better understanding. HTML <div id='iamdiv'>HELLO</div> <table> <tbody id='iamtbody' ...

A helpful guide on using workbox to effectively cache all URLs that follow the /page/id pattern, where id is a

Looking at this code snippet from my nodejs server: router.get('/page/:id', async function (req, res, next) { var id = req.params.id; if ( typeof req.params.id === "number"){id = parseInt(id);} res.render('page.ejs' , { vara:a , va ...

Tips on refreshing a view in react as data updates

Currently, I am delving into learning a variety of subjects such as Typescript, Express, and my newfound interests in REACT and RXJS. To aid in my studies, I created a Quick-List on Github, but encountered a question... "How can the view in React be upda ...

Believing that members possess a certain role when they actually do not

const { Discord, MessageEmbed } = require("discord.js"); module.exports = { name: "ban", description: "bans user from guild", execute(client, message, cmd, args, Discord) { const member = message.mentions.u ...

Is it possible to utilize Ajax submit requests within a (function($){...}(jQuery)); block?

As a PHP developer with some knowledge of JavaScript, I am currently using AJAX to send requests to the server. I recently came across the practice of enclosing all code within an anonymous JavaScript function like: (function($){ //code here }(jQuery)). Fo ...

What could be causing the error in the console when I try to declare datetime in Ionic?

I am just starting out with Ionic and Angular, but I seem to have hit a roadblock. The compiler is throwing an error that says: node_modules_ionic_core_dist_esm_ion-app_8_entry_js.js:2 TypeError: Cannot destructure property 'month' of '(0 , ...

Utilize Bootstrap modal to input information into the DataTables library

I am trying to use a bootstrap modal to insert data, but I am encountering an error on the action index. As a result, the button that I added is not functioning correctly. Can someone please review my code to see if there are any mistakes? User Action Con ...

Regular expression pattern for the #include directive

I'm currently developing a node.js JSON tool that involves incorporating external JSON files and merging them after performing nested lookups. I've hit a roadblock with regex patterns needed to validate the following scenarios: !include('oth ...

Implementing a password toggle feature on a form that extends Django's default Authentication Form

Incorporating a password toggle feature has become quite the challenge as I extend Django's AuthenticationForm to create my UserLoginForm. Attempting to implement this feature has proven difficult, especially since I have been unable to make use of th ...

How to dynamically disable a button using an attribute directive in an Angular application

I've implemented an attribute component that adds a spinner to a button: spinner-button.component.html: <ng-content></ng-content> @if (showSpinner()) { <span class="spinner-border spinner-border-sm"></span> ...

What could be the reason for routerLink not redirecting to the page after the user has logged out?

On my login page, I have a link labeled "Register", and on the register page, I have a link labeled "Login". To navigate between these pages, I used the following code: <p>Not a member? <a [routerLink]="['/register']">Regist ...

Utilizing a forwardRef component in TypeScript to handle child elements

Working with @types/react version 16.8.2 and TypeScript version 3.3.1. This forward refs example was taken directly from the React documentation with added type parameters: const FancyButton = React.forwardRef<HTMLButtonElement>((props, ref) => ...

Is it feasible to utilize Google Calendar API for JavaScript through npm install? Alternatively, can the Google Calendar API be utilized for Node.js in the browser within Next.js?

Looking to integrate the Google Calendar API as a library in your Next.js project without using _document.tsx? I have explored two potential approaches for achieving this: Utilize the google calendar api for JavaScript by installing it via npm Use the goo ...

Using PHP to extract all occurrences of window.location from an HTML document using regex

Is there a way to extract all the window.location instances in PHP? I have a list of URLs that I am fetching using cURL, saving the HTML content as a string, and now I need to identify and display all the occurrences of window.location separately. I atte ...