How to traverse a JSON file using TypeScript within an Angular application?

[
        {
            "title": "Marker 1",
            "innercontent": "the Porcelain Factory"
        },
        {

            "title": "Marker 2",
            "innercontent": "The Taj Mahal "

        },
        {
            "title": "Marker 3",
            "innercontent": "Golconda Fort"
        }
]

This snippet represents a JSON file structure.

<div *ngFor="let marker of currentmrkr">
      <div>
        {{ marker.title }}
      </div>
      <div>
        {{ marker.innercontent }}
      </div>
    </div>

The code above is from an HTML document.

import * as content from './content.json';
marker.addListener("click", () => {for(let item of content){
            if(marker.getTitle() == item.title){
              this.currentmrkr = item;
            }
          }
}

The TypeScript script snippet above shows an error that needs to be resolved.

 core.js:6260 ERROR TypeError: _content_json__WEBPACK_IMPORTED_MODULE_1___namespace is not iterable

How can we correctly iterate through the JSON object in TypeScript within Angular and import the file properly into the TypeScript file?

Answer №1

If you're looking to loop through JSON data in Typescript for tasks like pushing information to firebase, one useful library to consider is Lodash

import * as _ from 'lodash';

myfunction(json) {
    return new Promise((resolve) => {
      _.map(json, (e, i) => {
       _.keys(e).map(() => {
        this.afs.collection('library').doc('doc ' + i).set(e);
       })
      })
     resolve();
   })
  }

For a more detailed explanation, I've written a comprehensive blog post on this topic. Alternatively, if you have a basic JSON object in Typescript and want to display specific values in HTML, you can follow this method:

import { Component } from "@angular/core";

@Component({
  selector: "app-some-section",
  templateUrl: "./some-section.component.html",
  styleUrls: ["./some-section.component.scss"],
})
export class SomeSectionComponent {
  users = [
    {
      name: "Jacob",
      job: "Analyst",
      city: "California",
    },
    {
      name: "John",
      job: "Founder",
      city: "New York",
    },
  ];

  constructor() {}

}

Then in the HTML template:

<div class="card" *ngFor="let user of users">
    <h3 class="job">{{ user.job }}</h3>
    <h3 class="name">{{ user.name }}</h3>
    <h3 class="city">{{ user.city }}</h3>
</div>

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

encountered premature completion of hasBytesAvailable

My server is sending JSON data to my cocoa app. Upon receiving the data, the cocoa app processes it using the following code: case NSStreamEventHasBytesAvailable: NSLog(@"begin"); if (theStream == inputStream) { int len; uint8_t b ...

"Receiving an error message stating 'Was expecting 1 parameter, received 2' while trying to pass a useState function in TypeScript

I am encountering an issue with a component where I pass a useState setter to a utility function: export interface IData { editable: string[]; favourited: string[]; } const [data, setData] = useState<IData | undefined>(undefined) useEffect(() = ...

Access the name property from the package.json file using a bash script

I encountered this issue: str=`cat package.json` prop="name" my_val="$(node -e "console.log(JSON.parse(${str})[${prop}]);")" echo "$my_val" My goal was to extract the name property from the package.json file. However, I am facing a JSON.parse error: Syn ...

Transitioning an NX environment to integrate ESM

My NX-based monorepo is quite extensive, consisting of half a dozen apps, frontend, backend, and dozens of libs. Currently, everything is set up to use commonjs module types, as that's what the NX generators have always produced. However, many librar ...

Using JavaScript, pass an array containing a list of JSON values

I am attempting to store a list of JSON Objects in an array using JavaScript. Below is the list: [{"_id":1,"json":{"age":10,"name":"carlos"}},{"_id":2,"json":{"age":10,"name":"carlos"}}] Here is the code snippet I have written: var arrayResults = ' ...

Supabase guidelines for utilizing getServerSideProps in Next.js

I am creating a Trello-like application using Next.js and Supabase as my backend as a service. Within my Supabase table, I have set up certain policies: https://i.sstatic.net/gl5Si.png The policies function correctly on the client-side with this code sn ...

I am encountering an issue regarding the 'endpoint' property within my environment.ts file while working on an Angular 17 project

My goal is to incorporate the property endpoint from my environment.ts file into my service: export const environment = { production: false, endpoint: 'http://localhost:3000/api/cabin/' }; This snippet showcases my service: import {Injectabl ...

Error: The module 'fs' could not be located after running Rollup

Having encountered this issue, I understand that it has been a common question on the internet. I apologize for potentially duplicating the query. Despite trying various solutions found online, none have proven to be effective. The Problem: The problem ar ...

Which data structure is suitable for storing a JSON object?

Currently, I have a form set up in the following way: using (Ajax.BeginRouteForm( ... new AjaxOptions { HttpMethod = "POST", OnFailure = "OnFailure", OnSuccess ...

Using a for loop in Flot to display data from a JSON file

I am working on creating a dynamic flot graph that will adjust based on the data provided. The information for my flot graph is in JSON format, and here's an example of the dataset: { "total":[[1377691200,115130],[1377694800,137759],[1377698400,1 ...

An Error with jQuery Autocomplete: "Callback is not Defined"

I am currently working on a jQuery script that involves autocomplete and selecting the correct value on the client side. Here is my functional code without the selected value (it displays all username available in my JSON): $(function() { $( "#us ...

What is the most efficient way to add an element to a list in a JSON structure?

Currently, I am working on JavaScript and encountering an issue with my JSON object: var obj ={"name" : "objName", "dynamicList" :[]}; I have been adding items to my list using the following approach: obj.dynamicList["someStringID"] = {"watever"}; ...

Error: An unexpected character was encountered while trying to parse the object

Within a HAML template, I have the following code: .movie_container{"ng-repeat" => "movie in movieGroup | orderBy:'release_date'"} %a{:href => "#", "ui-sref" => ".container-big({value: '{{movie}}'})"} More info Upon cli ...

Submitting a nested object to a Spring MVC controller through JSON format

In my controller, I have defined a POST handler like this: @RequestMapping(value="/ajax/saveVendor.do", method = RequestMethod.POST) public @ResponseBody AjaxResponse saveVendor( @Valid UIVendor vendor, Bindin ...

Save JSON files within Hyperledger Fabric

I am looking to implement a private blockchain system that can efficiently store complex data structures like JSON documents. The concept is to have each transaction represented as a JSON document, potentially with different schemas. After researching, i ...

Generating Legible JavaScript Code from TypeScript

I am looking to maintain the readability of my compiled JS code, similar to how I originally wrote it, in order to make debugging easier. However, the typescript compiler introduces several changes that I would like to disable. For instance: During compi ...

Drawer in Material-UI has whitespace remaining at the corners due to its rounded edges

While using the Material UI drawer, I attempted to round the corners using CSS: style={{ borderRadius: "25px", backgroundColor: "red", overflow: "hidden", padding: "300px" }} Although it somewhat works, the corners appear white instea ...

json not cooperating with ajax, but operates smoothly when utilized independently

My current issue involves using JSON to read records. The method works flawlessly when I integrate it directly into the JavaScript code, as shown below: var events=[{eventId:"1", event_name:"wedding"},{eventId:"2", event_name:"interview"}] I can then loo ...

"Efficiently Distributing HTTP Requests Among Simultaneous Observers using RxJS

Currently, I am working on a feature in my Angular application that requires handling multiple concurrent fetches for the same data with only one HTTP request being made. This request should be shared among all the subscribers who are requesting the data s ...

To handle the input field efficiently in Angular, consider utilizing two <input type="radio"> elements

I am facing a challenge in my Angular 5 project where I have two radio buttons and need to dynamically update the value of formControlName and placeholder for an input field based on the selected radio button. How can I tackle this issue? <div clas ...