Creating dynamic keys using Typescript and JSON data format

Currently, I am developing an application using Typescript and React Native. Within my app, I have a JSON file containing information about poker hands that needs to be accessed.

The structure of the JSON data is as follows:

{
  "22": [
    [
      0,
      20
    ]
  ],
  "32o": [
    [
      0,
      20
    ]
  ],
  "32s": [
    [
      0,
      20
    ]
  ],
  "33": [
    [
      0,
      20
    ]
  ],

To import the JSON data, I use the following code:

import * as pdata from './push.json';

To access the data, this syntax can be used:

pdata['AA'][0][1]

However, when attempting to access the JSON using dynamically generated keys like so:

currentHand = '32o';
console.log(pdata[currentHand][0][1]);

An error message appears stating "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '...' No index signature with a parameter of type 'string' was found on type '{ "22": number[][];...'. This issue arises due to the inability to hardcode all possible key options given the large number of keys present in the dataset.

I have been exploring various solutions to resolve this issue but have yet to find one that effectively addresses it.

Answer №1

When you declare currentHand without using const, Typescript assumes that the value of currentHand can be changed and therefore assigns the type of string to it.

However, if you declare it with const:

import data from "./push.json";

const currentHand = "22";
console.log(data[currentHand][0][1]);

The type of currentHand will now be specifically "22" instead of just a general string, eliminating the error.

Due to the large number of keys, hardcoding all possibilities is impractical. I have searched for solutions but nothing has worked so far.

You can try this approach:

type DataKey = keyof typeof data; // DataKey type will be "22" | 32o" | "32s" | ...

const currentHand: DataKey = "22";
// or
const currentHand = "22" as DataKey;

console.log(data[currentHand][0][1]);

Another alternative method is:

import data from "./push.json";

const dynamicData = <Data>((<any>data));

type Data = {
  [key: string]: [number[]];
  // or if value structure is consistent
  [key: string]: [[number, number]];
};


let currentHand = "22";
console.log(dynamicData[currentHand][0][1]); 

Answer №2

I stumbled upon a solution to this problem by using the website . After saving the generated converter in a file named Convert.ts, I was able to access JSON data like so:

import * as pdata from './push.json';
import { Convert } from './Convert'
    
const pushHands = Convert.toHands(JSON.stringify(pdata));
var ch = '42o';
console.log(pushHands['default'][ch][0][1]);

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

Gathering the output from every function within an array of functions

I've searched extensively for a solution to this dilemma, but have had no luck so far. Therefore, I am turning to the community for help. Please feel free to direct me to any existing similar queries. My challenge involves working with an array of fu ...

The setting of the custom user agent in the Chrome Extension Manifest Version 3 is not functioning correctly

We currently have an extension that consists of only two files: manifest.json and background.js Despite the browser (Chrome version 112) not reporting any errors, we are facing an issue where the user agent is not being set to 'my-custom-user-agent&a ...

Dynamic data manipulation with Angular ReactiveForms

One of the challenges I am facing involves using formArray for my list of products. Specifically, I am trying to access the value of product_code in my .ts file similar to [ngModel] so that I can manipulate the data accordingly. Can anyone provide guidance ...

What is the best way to extract a JSON value using key-value pairs?

Here is the content that I am displaying from a custom wordpress post type using get-client-logos.php [{ "name": "First", "url": "http://example.com/image1.jpg"}, { "name": "Second", "url": "http://example.com/image2.jpg" }]​ I am attem ...

The useState variable remains unchanged even after being updated in useEffect due to the event

Currently, I am facing an issue in updating a stateful variable cameraPosition using TypeScript, React, and Babylon.js. Below is the code snippet: const camera = scene?.cameras[0]; const prevPositionRef = useRef<Nullable<Vector3>>(null); ...

Unable to retrieve a valid JSON from a freemaker collection

I am attempting to generate a functional JSON output (an array with x number of objects) from a freemaker ftl file. The code provided below works perfectly when there is only one object in the "loggedInUsers" array. However, if there is more than one obj ...

The functionality of .getJSON() in JSON/JQuery is not compatible with IE8 or IE9 browsers

It seems that this particular code is not functioning properly in IE8/IE9, and I am uncertain whether it is caused by the JSON or JQuery .getJSON() element. The main objective of this code is to retrieve data from foursquare and present it on a webpage. I ...

What is the significance of the error message "The Type 'Any' does not align with the 'Sequence' protocol" when trying to iterate through a 'JSON' result?

Currently I am deepening my knowledge in Swift programming. My latest project involves creating an app that can extract historical data from a website and present it visually in the form of a chart. For this task, I have been utilizing Alamofire to handle ...

Understanding the structure of JSON files without prior knowledge

Without any prior knowledge of the contents, I am seeking to understand the structure of a JSON object. For example, I could receive: [{"x":0,"y":0.4991088274400681,"z":7.489443555361306}, {"x":0,"y":0.7991088274400681,"z":7.489343555361306},{"x":0,"y":0. ...

Assigning value to a member variable in a TypeScript Angular class

Currently, I am in the process of learning Angular. To enhance my skills, I am developing a simple web application using Angular and Spring Boot. One challenge I encountered is assigning a variable to the member variable of a Class. import { Injectable } f ...

NPM: There are no valid TypeScript file rules specified

Currently working on a small project using React.JS. Whenever I execute : npm run start, the following message gets logged: Starting type checking and linting service... Using 1 worker with 2048MB memory limit Watching: /Users/John/Projects/myProject/src ...

Executing functions in Vue TypeScript during initialization, creation, or mounting stages

Just a few hours ago, I kicked off my Vue TypeScript project. I've successfully configured eslint and tslint rules to format the code as desired, which has left me quite pleased. Now, I'm curious about how to utilize the created/mounted lifecycl ...

Encountering a SyntaxError while utilizing framer-motion in Next JS

Currently, I am working with NextJS version 12.0.3 and integrating framer motion for animations into my project. However, regardless of the framer-motion library's capabilities, whenever I add a tag to any HTML element in my component, an error is tri ...

Error in Typescript: The data type 'string | undefined' does not meet the requirements of 'string | number | symbol' constraint

Working with typescript and react. Trying to dynamically adjust font size based on props (xs, sm, md, lg). Attempted using Record but encountering a typescript error. Error message: Type 'string | undefined' does not satisfy the constraint & ...

show image data from json source

Hey there! I am currently sending a JSON to JSP that contains a file URL. My goal is to display an image using this URL in AJAX. Can anyone assist me with this? //controller recordingInfo = recordingManager.getRecordingInfo(new Integer(recordingId)); ...

Issues arise with the escape key functionality when attempting to close an Angular modal

I have a component called Escrituracao that handles a client's billing information. It utilizes a mat-table to display all the necessary data. When creating a new bill, a modal window, known as CadastrarLancamentoComponent, is opened: openModalLancame ...

"Is there a way for me to retrieve the name of my object property and use it

I need some help with retrieving API results. I have a class structure as follows: public partial class Sample { [JsonProperty("classificator")] public List<Classificator> Classificator { get; set; } } public partial class Classificator { ...

Retrieve specific JSON information

Below is an example of JSON data: [{ "RM_Name": "Russ Martin", "Division": "East", "RM_Phone": "(603) 491-1259", "RC_Name": "Jacob Sucoff", "RC_Phone": "(800) 247-4154 x3403", "States_Covered": "MT,VT, NH, ME (all firms)", "La ...

Ionic 3 Plugin for Handling HTTP Requests

I am facing an issue while trying to send a POST request using the HTTP Cordova plugin. The JSON data sent to the server is not being formatted correctly (missing JSON brackets). Can someone assist me with this problem? Here is the import statement: impo ...

Utilizing WebWorkers with @mediapipe/tasks-vision (Pose Landmarker): A Step-by-Step Guide

I've been experimenting with using a web worker to detect poses frame by frame, and then displaying the results on the main thread. However, I'm encountering some delays and synchronization issues. My setup involves Next.js 14.0.4 with @mediapip ...