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

Could anyone provide an explanation for the statement "What does '[P in keyof O]: O[P];' signify?"

As a new Typescript user looking to build a passport strategy, I came across a line of code that has me completely baffled. The snippet is as follows: here. The type StrategyCreated<T, O = T & StrategyCreatedStatic> = { [P in keyof O]: O[P]; ...

The type 'string | AddressInfo' does not include a 'port' property and does not have a string index signature

When running in { port }, I encountered the following error: Type 'string | AddressInfo' has no property 'port' and no string index signature. How can I resolve this issue? Code: import * as express from 'express' const app ...

When working with Angular 12, the target environment lacks support for dynamic import() syntax. Therefore, utilizing external type 'module' within a script is not feasible

My current issue involves using dynamic import code to bring in a js library during runtime: export class AuthService { constructor() { import('https://apis.google.com/js/platform.js').then(result => { console.log(resul ...

The Unhandled Promise Rejection Warning in mocha and ts-node is due to a TypeError that arises when attempting to convert undefined or null values

I've been encountering issues while setting up ts-node with mocha, as the test script consistently fails. I attempted to run the following commands: mocha --require ts-node/register --extensions ts,tsx --watch --watch-files src 'src/**/*.spec.{ ...

Ensuring that files adhere to the required format, whether they be images

Three separate input fields are being used, each with its own name for identification. A validation method is called to ensure that the files selected in these input fields are not duplicates and that they are either images or PDFs but not both. While thi ...

Determine in React whether a JSX Element is a descendant of a specific class

I am currently working with TypeScript and need to determine if a JSX.Element instance is a subclass of another React component. For instance, if I have a Vehicle component and a Car component that extends it, then when given a JSX.Element generated from ...

Sharing information between Angular components

Having recently started using Angular, I'm facing an issue with passing an array to a different component that is not parent or child related. What I aim to achieve is: upon selecting rows from the first component table, a new view should open up disp ...

What is the best way to transform an array containing double sets of brackets into a single set of brackets?

Is there a way to change the format of this list [[" ", " ", " ", " ", " ", " ", " ", " ", " ", " "]] to look like [" ", " ", " &qu ...

What is the role of @Output and EventEmitter in Ionic development?

I'm currently working on integrating Google Maps and Firebase database. My goal is to save my location in the Firebase database and transfer data using @Output and eventEmitter. However, I am facing an issue where pickedLocation has a value but this.l ...

How to access a specific key in a JSON string using square brackets in PHP

My current challenge involves dealing with an array: [{"title":" \ud83c\uddfa\ud83c\udde6 \u041b\u0443\u0447\u0448\u0435\u0435 \u043a\u0430\u0437\u0438\u043d\u04 ...

The styled component is not reflecting the specified theme

I have a suspicion that the CSS transition from my Theme is not being applied to a styled component wrapped in another function, but I can't pinpoint the exact reason. I obtained the Basic MUI Dashboard theme from this source and here. Initially, inte ...

Having trouble accessing an object in a post request with Axios, VueJS, and Laravel

I'm facing an issue with sending my post data to the controller in order to access it via an object. Although the data is being passed successfully, I'm unable to access any of the items within that object, which seems quite perplexing. Below is ...

Typescript Tooltip for eCharts

I'm working on customizing the tooltip in eChart v5.0.2 using Typescript, but I'm encountering an error related to the formatter that I can't seem to resolve. The error message regarding the function keyword is as follows: Type '(param ...

Monitor a universal function category

Trying to implement a TypeScript function that takes a single-argument function and returns a modified version of it with the argument wrapped in an object. However, struggling to keep track of the original function's generics: // ts v4.5.5 t ...

Implementing TypeScript inheritance by exporting classes and modules

I've been struggling with TypeScript's inheritance, it seems unable to resolve the class I'm trying to inherit. lib/classes/Message.class.ts ///<reference path='./def/lib.d.ts'/> ///<reference path='./def/node.d.ts& ...

Troubleshooting issues with the delete functionality in a NodeJS CRUD API

I've been struggling to implement the Delete functionality in my nodejs CRUD API for the past couple of days, but I just can't seem to get it right. As I'm still learning, there might be a small detail that I'm overlooking causing this ...

Rendering a Subarray using Map in ReactJS

I have an object containing data structured like this: [{"groupid":"15","items":[ {"id":"42","something":"blah blah blah"}, {"id":"38","something":"blah blah blah"}]}, {"groupid":"7","items": [{"id":"86","something":"blah blah blah"}, {"id":"49","somethin ...

Encountering an issue while trying to execute the command "ionic cordova build android --prod --release

Currently, I am facing an issue while trying to build my apk for deployment on the Play Store. The error message is causing a time constraint and I urgently need to resolve it. Any help or suggestions regarding this matter would be greatly appreciated. ...

Searching for JSON data within a specific column in SQL Server 2012

Within my SQL Server 2012 table, there is a column that holds JSON data as shown below. [{"bvin":"145a7170ec1247cfa077257e236fad69","id":"b06f6aa5ecd84be3aab27559daffc3a4"}] I am now looking to incorporate this column's data into a query like the on ...

How can I use regex within a pipe to split a string in Angular 4?

I need to implement a method where I can split a string based on special characters and spaces in the given regex format, excluding "_". Example: #abc_xyz defgh // output #abc_xyz Example: #abc@xyz defgh // output #abc Example: #abc%xyz&defgh // out ...