Having difficulty retrieving JSON properties that include hyphens or numerical characters in the key - a challenge with Rollup and TypeScript

Trying to load a large JSON file using import. This JSON file contains an object with keys that have numbers and hyphens. The issue arises when trying to access keys with hyphens or numbers as it returns undefined.

Using Rollup for building due to Svelte usage, had installed the json() plugin for importing, but seems to have trouble parsing object keys.

Noticed this while looping through the object - properties with hyphens return undefined while single-word ones work fine.

An example of an object that can be accessed without issues:

"accusoft": {
    "changes": [
      "5.0.0"
    ],
    "ligatures": [],
    "search": {
      "terms": []
    },
    "styles": [
      "brands"
    ],
    // More data...
  }

And here's an example object that results in undefined when accessed:

"accessible-icon": {
    "changes": [
      "5.0.0"
    ],
    "ligatures": [],
    "search": {
      "terms": [
        "accessibility",
        "handicap",
        "person",
        "wheelchair",
        "wheelchair-alt"
      ]
    },
    // More data...
  }

Aware that hyphens are seen as operators, so utilizing square brackets for property access.

This is the TypeScript code being used:

import * as iconsList from '../../data/fontawesome-5/metadata/icons.json';
export interface IconEntryCollection {[key: string]: IconEntry; }

//Some code goes here

constructor(){
   this.iconEntries = iconsList as IconEntryCollection;
   this.icons = [];
}

//Some code goes here

console.log(this.iconEntries['accessible-icon']) // Returns undefined

Unsure if the issue lies in a mistake on my end or if Rollup isn't parsing the JSON accurately. Can provide additional code examples if needed.

Answer №1

When it comes to JavaScript, using dashes in object keys can be a tricky situation that requires careful handling at all times.

To address this issue, the Roll-up JSON plugin removes all dashes and converts the following word identifier to uppercase. For example, accessible-icon becomes accessibleIcon.

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

Creating a model and assigning values in TypeScript

I am currently developing an angular application and need to send data to a post API. The JSON structure I am working with is as follows: { "name": "julie", "id": 1, "PersonalDetails": { "hom ...

The mat-table's data source is failing to refresh and display the latest

When I click on a column header to sort the table, a function should trigger and update the data. However, the data is not updating as expected. Below is the code for the function and the table: <table mat-table #table [dataSource]="dataSourceMD&qu ...

Sorting is ineffective when employing JSON_ARRAYAGG

When I execute the following queries: SELECT name FROM customers ORDER BY name The results are displayed in alphabetical order. However, if I run this query: SELECT JSON_ARRAYAGG(name) FROM customers ORDER BY name The results come out in a specific orde ...

How can one accurately pair the key and its corresponding value from an array of objects to create a new object containing only that key?

In my JavaScript code, I am attempting to create a function that can match a specific key with an array of objects fetched from an API. This matching process is based on two parameters obtained from the API: a key (which is a string) and an array of object ...

A step-by-step guide on extracting a single JSON element and parsing it in Python without any external libraries

I'm facing a challenge with this problem, especially since I'm not very familiar with JSON. But let me give it a shot. I have a dataset that I've processed in pandas, but it may not be usable later on. I exported it as both JSON records and ...

Tips on modifying the structure of a JSON array using a loop

Hello, I am currently extracting data from an API, but I need to transform the data into a different format in order to pass it to a function successfully. The reason for this is that I have a chart that only accepts data in a specific format for it to dis ...

Is there a way to execute code precisely at a specific timestamp?

I am working with a backend that has a REST API containing an array of objects with timestamps (indicating when events occur in the game) along with respective values. {"timestamp":1623320102097,"crops":[0,5,9]} Is there a way to trigg ...

Error in Typescript: Array containing numbers is missing index property `0`

This is the code for my class: class Point{ coordinates: [number, number, number]; constructor(coordinates: [string, string, string]) { this.coordinates = coordinates.map((coordinate) => { return Math.round(parseFloat(coordinate) *100)/ ...

What is the best approach to decode this JSON object in Swift 3.0?

Currently, I am in the process of parsing a JSON string that is being returned from an API. The format of the JSON string that I am working with is shown below. QuerySearchResult":{ "StartAt":"1", "Count":"40", "TotalAvailable":"500", "Items":[ {"TITL ...

Organize hierarchical JSON data using Pandas and Python

I'm currently working on standardizing a sample dataset that looks like this: { "2018-04-26 10:09:33": [ { "user_id": "M8BE957ZA", "ts": "2018-04-26 10:06:33", "message": "Hello" } ], "2018-04-27 19:10:55": [ { ...

Is node.js necessary for running TypeScript?

Node.js is necessary for installing TypeScript. I believe that TypeScript utilizes Node.js to compile .ts files into .js files. My concern is whether the generated .js file needs node.js in order to function properly. From what I've observed, it seem ...

Tips on adding a third table to a JsonResult and implementing it in the Details method of my controller

My second attempt to resolve this issue has me stumped, as I cannot figure out an alternative approach. [HttpGet] public JsonResult FetchStudentBadgesList (int CohortProgramEnrollmentID) { db.Configuration.ProxyCreationEnabled = false; ...

``Should one prioritize the use of Generics over Inheritance, or is there a better way

We are currently in the process of implementing new contracts for our icons system, and we have encountered a debate on which approach is more preferable. Both options result in the same interface: Using Generics -> Although the interface may be less ...

Transforming JSON data in a node.js environment

When attempting to convert a JSON response code, I am consistently receiving a string array instead. The header fields are dynamic based on the table being queried, so hardcoding them is not an option. The JSON response looks like this: { "records": [ ...

Injecting Dependencies with Angular 2 and the Ability to Include Optional Parameters

One issue I'm facing is that I have multiple components in my Angular 2 application that require the same dependency. This specific dependency needs a string for the constructor. How can I instruct angular2 to use a specific instance of this type for ...

What is the method to incorporate the current time into a date object and obtain its ISO string representation?

I'm using a ngbDatePicker feature to select a date, which then returns an object structured like this: {year:2020, month:12, day:03} My goal is to convert this date into an ISOString format with the current time. For example, if the current time is 1 ...

Experiencing a service error when trying to load in certain browsers, although it does work properly in Chrome and

I am facing an issue with my service method which is showing errors in multiple browsers including Internet Explorer 8, Chrome, and Firefox 8.0.1. The error message is: OPTIONS http://abc/AddRating 405 (Method Not Allowed) Interestingly, the service met ...

File writing issues are plaguing NodeJS, with middleware failing to function as well

I am facing a challenge with my middleware that is supposed to write JSON data to a file once the user is logged in. However, I am encountering an issue where no data is being written to the file or displayed on the console when the function is executed. ...

Combining a JSON file and a CSV file into a pandas dataframe for analysis

I have a JSON file with geographic data that includes information on population counts for different areas represented by WK_CODE. { "type" : "FeatureCollection", "name" : "NBG_DATA.CBSWBI", "feature ...

Checking if a string in Typescript contains vowels using Regex

Is there anyone who can assist me with creating a regex to check if a string contains vowels? EX : Hi Team // True H // False I have tried using the following regex but it's not giving me the desired outcome. [aeiou] ...