Uncovering the value of a Nested JSON object in a JSON file with Typescript

As a beginner in Typescript, I am currently working on parsing a nested JSON file containing segments and products. My goal is to extract the value of the product and display it on the console.

Here is the structure of the JSON File :

{
    "int": {
        "name": "internal",
        "products": {
            "test": "Internal Test from Actions"
        }
    },
    "tst": {
        "name": "test",
        "products": {
            "action": "Test Actions"
        }
    }
}

In this example, my objective is to retrieve the JSON value of "Test Actions", identify its corresponding key action, and store it as a string variable.

The task at hand involves iterating through the products within Typescript code, locating the desired value, retrieving its associated key, and storing it for further processing.

Answer №1

If you want to extract keys and values from an object, you can use a function like the one below:

const displayKeysAndValues = (object) => {
  for (const key of Object.keys(object)){
      console.log(key);
      console.log(object[key]);   
  }
};

const obj = {
  'key1': 456,
  'key2': 'another value'
};

displayKeysAndValues(obj);

It's important to note that this example assumes the object only contains primitive data types at the top level. If your object has nested structures, you'll need to handle those differently.

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

Experiencing a ResponseStatusLine issue while trying to download a .json file from an API site

Recently, I set out to develop a small app using the Discogs API for my own personal use. The aim was to easily search for individual artists and their albums. Thanks to an unofficial Discogs C# app, I was able to achieve this successfully. However, I enco ...

The promise of returning a number is not compatible with a standalone number

I am currently working on a function that retrieves a number from a promise. The function getActualId is called from chrome.local.storage and returns a promise: function getActualId(){ return new Promise(function (resolve) { chrome.storage.syn ...

Obtain the value of a key from a collection of JSON objects using NodeJS

I'm dealing with a JSON object that is presented as a list of objects: result=[{"key1":"value1","key2":"value2"}] In my attempts to extract the values from this list in Node.js, I initially used JSON.stringify(result) but was unsuccessful. I then tr ...

Struggling to retrieve accurate JSON data from a hashmap using Gson

Utilizing GSON and hashmap to retrieve JSON data from a Pojo class. Here is an example of the Pojo Class: public class NetworkConfiguration { @SerializedName("GUID") @Expose private String gUID; @SerializedName("Name") @Expose pri ...

Encountering an issue with MUI Props: "Must provide 4 to 5 type arguments."

I'm attempting to use a custom component and pass in AutocompleteProps as a prop, all while utilizing typescript. Here's my current setup: type Props = { autoCompleteProps?: AutocompleteProps<T> label: string loading?: boolean } cons ...

An error has been encountered: JSONDecodeError Unable to find expected value at line 1, column 1 (character 0) While trying to address the previous error, a new exception occurred:

import urllib.request import json def printResults(data): theJSON = json.loads(data) if "title" in theJSON["metadata"]: print(theJSON["metadata"]["title"]) count = theJSON["me ...

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 ...

How to safely add multiple objects to an array in TypeScript & React without replacing existing objects - Creating a Favorites list

I'm in the final stages of developing a weather application using TypeScipt and React. The last feature I need to implement is the ability for users to add queried locations to a favorites list, accessed through the "favorites" page. By clicking on a ...

Issues with utilizing Fetch API and JSON Data

I'm encountering some difficulties while trying to interact with my json file. I am using the fetch API to retrieve my json file but, unfortunately, when I log the response to the console, I don't see any data returned. Instead, what appears is a ...

Is it possible to incorporate a function within a JSON object structure?

I'm working on developing a library with the main requirement being that users can only utilize JavaScript to implement it. The idea struck me to leverage JSON and AJAX for this purpose. Is it feasible to define functions within JSON? Just to clarify ...

"Send the selected radio button options chosen by the user, with the values specified in a JSON format

My current task involves inserting radio button values into a MySql database using Angular. The form consists of radio buttons with predefined values stored in a json file. Below is an example of how the json file is structured: //data.json [{ "surve ...

Tips on Comparing Date and Time in Android Platform

Two dates are present, date1 (current) and date2 obtained from a JSON string as 2016-07-09 21:26:04. I need to perform a comparison between these two dates using the following logic: if(date1 < date2){ } ...

Obtain an instance of a class within a function that is contained within an instance object in TypeScript/Angular

There is a separate object responsible for managing a specific dialog box in my application. The challenge lies in accessing the instance of the class, even though the functions are self-explanatory. I attempted to use the conventional method of that = thi ...

Ways to interpret a json object containing various key values?

We are attempting to extract data from a JSON object that contains varying key-value pairs each time. { "FirstKey": "FirstValue", "SecondKey": "SecondValue", "ThirdKey": "ThirdValue", "FourthKey": "FourthValue", "FifthKey": "FifthValue", ..... ...

How to use RxJs BehaviorSubject in an Angular Interceptor to receive incoming data

Being a newcomer to rxjs, I grasp most operators except for the specific use case involving BehaviorSubject, filter, and take. I am working on renewing an oauth access and refresh token pair within an Angular interceptor. While reviewing various codes fro ...

Setting up initial values for a JSON array in an AJAX function upon the document being fully loaded

I am currently developing an Ajax function that passes values from an array. My goal is to simplify the process of handling various translations by creating a JSON file containing all the required translations and then making it available to my main Ajax f ...

generate JSON files for each CSV row using PHP

After stumbling upon this code snippet that turns CSV rows into objects, I was intrigued: $fp = fopen('test.csv', 'r') or die("**! can't open file\n\n"); $i = 0; while ($csv_line = fgetcsv($fp, 1024)) { $i++; $js ...

Ways to eliminate additional data points on the x-axis in Highcharts

I'm currently using Highcharts to plot data for specific ID's, but I'm experiencing a display issue where extra data points are showing up on the x-axis. I only want to show certain data points on the x-axis and am not sure how to remove the ...

What is the correct method for sending JSON data to the JSONResult function within an MVC controller?

I am attempting to pass my email and password to the jsonresult method in my home Controller. The values of email and password are displayed in the first alert, but when I try to pass userCredential to the data, it shows an alert with "undefined". The valu ...

Transfer the value of one column in a data table to another location

I'm attempting to transfer a jQuery column value from one column to another. In my table, I have columns named ID and Title. The Title column should display the value from the ID column. Despite my efforts, I haven't been successful in achievin ...