Getting into nested information in a JSON string using TypeScript

I need help accessing the data values (data1, data2, and date) from this JSON structure. I would like to store these values in an array that can be sorted by date:

{
"07" : {
  "07" : {
    "data1" : "-1",
    "data2" : "test",
    "date" : "1995-07-07"
  },
  "08" : {
    "data1" : "1",
    "data2" : "test",
    "date" : "1995-07-08"
  },
  "09" : {
    "data1" : "-1",
    "data2" : "test",
    "date" : "1995-07-09"
  },
  "10" : {
    "data1" : "-1",
    "data2" : "test",
    "date" : "1995-07-10"
  }
},
"08" : {
  "07" : {
    "data1" : "1",
    "data2" : "test",
    "date" : "1995-08-07"
  },
  "08" : {
    "data1" : "1",
    "data2" : "test",
    "date" : "1995-08-08"
  },
  "09" : {
    "data1" : "1",
    "data2" : "test",
    "date" : "1995-08-09"
  }
}
}

Since my keys are not constant, I am unsure of their values in advance.

Answer №1

A solution to filling in missing functionality for Object.entries:

const reduce = Function.bind.call(Function.call, Array.prototype.reduce);
const isEnumerable = Function.bind.call(Function.call, Object.prototype.propertyIsEnumerable);
const concat = Function.bind.call(Function.call, Array.prototype.concat);
const keys = Reflect.ownKeys;

if (!Object.values) {
    Object.values = function values(O) {
        return reduce(keys(O), (v, k) => concat(v, typeof k === 'string' && isEnumerable(O, k) ? [O[k]] : []), []);
    };
}

if (!Object.entries) {
    Object.entries = function entries(O) {
        return reduce(keys(O), (e, k) => concat(e, typeof k === 'string' && isEnumerable(O, k) ? [[k, O[k]]] : []), []);
    };
}

Sample code:

for (const [key, value] of Object.entries(myObject))
        {
            for (const [key2, value2] of Object.entries(value))
            {
                value2.data1;
                value2.data2;
                value2.date;
            }
        }

To avoid using Object.entries, you can enumerate an object like this.

for (var key in myObject)
{
    for (var key2 in myObject[key])
    {
        myObject[key][key2].data1;
        myObject[key][key2].data2;
        myObject[key][key2].date;
    }
}

Answer №2

If you want to extract all the key names from your JSON data and store them in an array, you can use the following method:

const keys = Object.getOwnPropertyNames(jsonData);

For instance, if your JSON data includes keys '07' and '08', the above code will create an array ['07', '08']. To access the actual objects corresponding to these keys, you can iterate through the keys like this:

keys.forEach((key) => {
    const object = Object.getOwnPropertyDescriptor(jsonData, key);
})

You can then retrieve the names of the keys within these objects by iterating again:

objects.forEach((object) => {
    const subKeys = Object.getOwnPropertyNames(object);
})

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

How to eliminate escape characters in Jquery Post requests

I've come across several questions similar to mine, but I haven't found a satisfactory answer yet. My issue is as follows: I'm trying to convert a JQuery object into a Json String and then send this string to a PHP webpage. The sending part ...

The error `TypeError: Unable to access properties of an undefined value (reading 'authService')` occurred

I'm attempting to check if a user is already stored in local storage before fetching it from the database: async getQuestion(id: string): Promise<Question> { let res: Question await this.db.collection("questions").doc(i ...

Leveraging polymorphism during deserialization with Jackson and MrBean

Currently, I am utilizing Jackson to deserialize JSON into Java POJOs. By registering the MrBean module with my object mapper, I can easily define various interfaces and have the POJOs generated automatically based on those interfaces. One specific requir ...

Ways to extract information from a JSON dataset

[{"id":7,"message":"This is just a sample message","taker_id":"131","giver_id":"102","status":"0","stamp":"2016-08-11"}] Here is my answer. I am attempting to retrieve some data. I have attempted using data.id but it is unsuccessful and gives me undefined ...

Error: The property 'target' cannot be read

I'm seeking to enhance a value by pinpointing a specific element within a loop. <div *ngFor="let item of items; let i = index"> <ion-button (click)="increment(i)"> <ion-icon name="add"></ion ...

Is there a way to verify if a value is undefined before including it as an object field?

I'm currently working on an Angular project and I have a query regarding TypeScript. It's about correctly handling the scenario where a field should not be included in an object if its value is undefined. In my code, I am initializing an object ...

What is the process for declaring global mixins and filters on a Vue class-based TypeScript component?

Recently, I've been working on incorporating a Vue 2 plugin file into my project. The plugin in question is called global-helpers.ts. Let me share with you how I have been using it: import clone from 'lodash/clone' class GlobalHelpers { ...

Troubleshooting native web worker issues in Angular 11 - Addressing the Element Bug

After upgrading Angular to version 11, I encountered issues with utilizing web workers for heavy data processing in my project. Previously, I used webworkify-webpack (https://www.npmjs.com/package/webworkify-webpack), but it stopped working post-migration. ...

Enhancing the JSON output of ActionResult in Asp WebApi for a more aesthetically

Currently developing a REST service using ASP.NET Core Web API and hoping to introduce a 'prettify' parameter to my endpoint in order to have the response JSON formatted with indentation for better readability in web browsers. I'm curious a ...

Using TypeScript in .cshtml Razor Files

Recently, I embarked on a new project utilizing the ASP.NET-MVC framework. For this particular project, I decided to opt for TypeScript over JavaScript. While Visual Studio provides excellent support for TypeScript, I encountered some compatibility issues ...

employing express.json() post raw-body

Within my Express application, I am aiming to validate the length of the request body and restrict it irrespective of the content type. Additionally, I wish to parse the body only if the content type is JSON. How can I go about accomplishing this? Curren ...

"Are you experiencing issues with the Ajax Success function not getting triggered upon returning from the Controller

Can anyone help me with my jQuery code? Here it is: $("#create").click(function(e) { var myModel = { "TribeName": $('#TribeName').val() }; var jsonToPost = JSON.stringify(myModel); $.aja ...

How to transfer a parameter in Angular 2

I am currently facing a challenge in passing a value from the HTML file to my component and then incorporating it into my JSON feed URL. While I have successfully transferred the value to the component and displayed it in the HTML file, I am struggling to ...

Tips for displaying JSON in C# using Nancyframework

I am facing an issue with displaying data from a JSON file named file.json on my screen when I access the URL localhost:8080/data. The attempted solution resulted in an error being displayed on the webpage as shown below: System.Collections.Generic.List` ...

Substitute specific characters in a string using Regex or Gsub

Struggling to find the correct answer, I'm considering altering the question. Presented below is a JSON code snippet: [ { "section_id": "58ef93aaa310c97c0c16bcd2", "name": "Name1", "slug": "slug1" }, { "section_id": "58ef93aaa3 ...

Check the @versionColumn value for validation prior to the entity save operation in TypeORM

I am currently in the process of saving data in a PostgreSQL database using TypeORM with NestJS integration. The data I am saving includes a version property, which is managed using TypeORM's @VersionColumn feature. This feature increments a number ea ...

JavaScript - Modifying several object properties within an array of objects

I am attempting to update the values of multiple objects within an array of objects. // Using a for..of loop with variable i to access the second array and retrieve values const AntraegeListe = new Array(); for (let i = 0; i < MESRForm.MitarbeiterL ...

What is the best way to determine the frequency of each element in a two-dimensional array that has been read from a file?

Having trouble with the Array.count method on a two-dimensional array. I'm loading my two-dimensional array from a file that was previously stored, something like this: [[1, 1, 1, 1, 1, 2, 2, 1, 1, 1], [1, 1, 1, 1, 1, 2, 2, 1, 1, 1], [1, 1, 1, 1, 1, ...

Splitting JSON data into groups using Python 3

Looking to divide the actual value into separate dynamic groups represented as an array of objects. c = { 'Date#1': '07/03/2018', 'Item#1': '789807', 'Description#1': 'Wooden Block ...

Utilizing JSON for the setAttribute() method

While I've made progress on this issue, I've encountered numerous confusing methods. The goal is to utilize the key:value pairs in attr{} for the setAttribute() function without relying on any framework. If anyone could provide a straightforward ...