Transform data into JSON format using the stringify method

I am facing an issue with my TypeScript code where I need to retrieve specific information from a response. Specifically, I want to output the values of internalCompanyCode and timestamp.

The Problem:

An error is occurring due to an implicit 'any' type because the index expression is not recognized as a 'number'.(
//const json = JSON.stringify(result, null, 2)
// json is the result of JSON.stringify(...)
const json = [
  {
    "internalCompanyCode": "007",
    "moreInfo": [
      {
        "dimensions": {
          "height": 27,
          "width": 31,
          "length": 61
        },
        "currenStatus": {
          "arrived": {
            "timestamp": "10:00:12"
          }
        }
      }
    ]
  }
]

console.log(json['internalCompanyCode'])
console.log(json['moreInfo']['dimensions']['height'])

Answer №1

If you want to retrieve data from the result, there is no need to convert it to a string first. You can directly access the properties of the result object before converting it to JSON or parsing JSON back to the result.

console.log(result[0]['internalCompanyCode']) //007

console.log(result[0]['moreInfo'][0]['currenStatus']['arrived']['timestamp']) // 10:00:12

console.log(result[0]['moreInfo'][0]['dimensions']['height']) //27

Answer №2

The data you are working with is in JSON format, but it appears to be structured as a list. In order to access specific values within this list, you will need to use syntax similar to json[0]['internalCompanyCode']

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

Enable the Angular button only when the radio button has been selected

Just starting out with Angular and I have a query. This is a scenario for my project at work. https://i.stack.imgur.com/R3SxA.png In this screenshot, I want to enable the "ajouter" button when at least one radio button is selected in the secure chest (s ...

Service function in Angular 2 is returning an undefined value

There are two services in my project, namely AuthService and AuthRedirectService. The AuthService utilizes the Http service to fetch simple data {"status": 4} from the server and then returns the status number by calling response.json().status. On the ot ...

Guide on traversing and modifying properties within a intricate JSON structure using Node.js

Is there a way to update the value of "message" for "chatTemplateId":"5" and "mid":"b" to "Test2" in the JSON data below using node-js/javascript? In C# I would have used LINQ, but I'm not sure how to achieve this in an optimized manner in JavaScript/ ...

Typescript requires that the argument passed is undefined

Typescript: 2.4.1 I am exploring the creation of a helper function to produce redux action creators. Here is what I have: interface IAction<T extends string, P = undefined> { type: T; payload: P; } function createAction<T extends strin ...

Using TypeScript to ensure the correct typing for the return type of AsyncThunk when utilizing the 'unwrapResult' method from Redux Toolkit

Struggling to determine the appropriate return type for an AsyncThunkAction in order to utilize it with the unwrapResult method from Redux Toolkit (refer to: Redux Tookit: Unwrapping Result Actions): Here is how the Async thunk is declared in the Slice: e ...

Updating the parent navigation bar after a successful login in a child component in Angular4

In my Angular4 project, I have set up a login page. Within the parent app.component file, I have included a navigation bar with login and signup buttons. Upon successful login, the login and signup buttons should be hidden, and the username should appear i ...

Creating a TypeScript type or interface that represents an object with one of many keys or simply a string

I am tasked with creating an interface that can either be a string or an object with one of three specific keys. The function I have takes care of different errors and returns the appropriate message: export const determineError = (error: ServerAlerts): ...

Guide on formatting the API response using a callback function in Angular development

How can I reformat my API response using a callback function and access the data within the angular subscribe method? I attempted to use mergemap but it didn't work as expected. this.http.get('https://some.com/questions.xml', {headers, res ...

Transform ECMAScript Observable / Zen Observable into RXJS Observable

I currently have an ECMAScript Observable that is compliant with specifications, specifically sourced from the wonka library. I am facing challenges in converting this type of observable to an rxjs 6 observable. It appears that this conversion was possibl ...

Send the ViewModal object from the JavaScript file to the backend code

I am facing an issue with my JavaScript file which calls a method in my code-behind. In order to pass my ViewModel to the save method, EXAMPLE 2, I have created a parameterless default constructor, EXAMPLE 1. However, this setup results in a 500 error. Upo ...

Transforming a Dictionary into a MySql 8 Database

After storing a JSON structure in a MySql table, I now have the task of extracting specific pieces buried within the depths of this JSON string months later. { "id": "000689ba-9891-4d82-ad13-a7b96dc08ec4", "type": &quo ...

Trigger a dispatched action within an NGRX selector

I want to ensure that the data in the store is both loaded and matches the router parameters. Since the router serves as the "source of truth," I plan on sending an action to fetch the data if it hasn't been loaded yet. Is it acceptable to perform the ...

Steer clear of including numerous variable values in Angular 2 while adjusting the class of selected items

Here's a question from someone who is new to Angular 2 and looking for an efficient way to change the active CSS class of tabs without using the router: activeTab: string; switchActiveTab(newTab: string) { this.activeTab = newTab; } <div clas ...

Utilizing ES6 JavaScript for Creating Static Methods and Angular 2 Services

During the development of an Angular 2 app involving multiple calculation services, I encountered some interesting questions: Is it beneficial to use static in an Angular service provided on the application level? Or is it unnecessary? How does a static ...

What is the best way to eliminate a specific set of characters from a string using TypeScript?

Imagine you have the following lines of code stored in a string variable: let images='<img alt="image1" height="200" src="image1.jpg" width="800"> <img alt="image2" src="image2.jpg" height="501" width="1233"> <img alt="im ...

Real-time data feeds straight from JSON

Currently, I have a JSON file that is generated dynamically and it contains match information along with a unique id. This JSON data is categorized into live, upcoming, and recent arrays. Being new to Javascript, I am unsure about the best approach to crea ...

Using Typescript: accessing all properties from a specified type while excluding one

Currently working in React, I am interested in extending my type from another, with the exception of some props. This is how I want to approach it : import React from 'react'; import { withTheme } from 'styled-components'; import SvgBa ...

How can I assign a type to an array object by utilizing both the 'Pick' and '&' keywords simultaneously in TypeScript?

As a beginner in TypeScript, I am looking to declare a type for an array object similar to the example below. const temp = [{ id: 0, // number follower_id: 0, // number followee_id: 0, // number created_at: '', // string delete_at: &ap ...

Parsing the id property in C# with MongoDB deserialization

Here's a snippet of my class structure: public class Object { [JsonConverter(typeof(ObjectIdConverter))] public ObjectId Id { get; set; } public List<Record> Records { get; set; } } public class Record { [JsonConverter(typeof(O ...

What is the solution for resolving an Element that implicitly has said it has an 'any' type as the expression of type 'string' cannot be used to index the type?

Having some trouble with TypeScript in my React project and encountering this error message. Error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ paymentMethod ...