How to convert JSON data (excluding headers) into a string array using TypeScript

I am attempting to extract the raw data from the JSON without including the headers. For example, I want to retrieve '1' but not 'ID', or 'foo' but not 'Name'.

[{ID = 1, Name = "foo", Email = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="34525b5b74525b5b1a575b59">[email protected]</a>"},
{ID = 2, Name = "bar", Email = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f4969586b4969586da979b99">[email protected]</a>"}]

The rationale behind excluding the headers is due to the dynamic nature of the data. The JSON response may contain varying fields per object in different calls. As seen below, my interface only includes a string because the structure of the data is unpredictable.

Below is the TypeScript code I am using to process the data:

import { Component } from '@angular/core';
import { Http } from '@angular/http';

@Component({
    selector: 'fetchdata',
    template: require('./fetchdata.component.html')
})
export class FetchDataComponent {
    public rowData: RowInfo[];

    constructor(http: Http) {

        http.get('/api/SampleData/DatatableData').subscribe(result => {
            // This is where the transformation should occur
            // Currently, this does not function as intended
            var dataCarrier = result.toString();
            JSON.parse(dataCarrier).forEach(item => {
                this.rowData = item.name;
            });
        });
    }
}

interface RowInfo {
    rowData: string;
}

How can I extract and pass just the individual pieces of JSON data through to the interface while handling multiple rows within the same object?

Answer №1

If you want a more modern approach using ES6, you can achieve it by getting an array with each object's values stored in individual arrays.

JSON.parse(dataCarrier).map(Object.values)

For example, if your data looks like this:

[{ID = 1, Name = "foo", Email = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e3831311e383131703d3133">[email protected]</a>"},
{ID = 2, Name = "bar", Email = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ff9d9e8dbf9d9e8dd19c9092">[email protected]</a>"}]

// =>

[[1, "foo", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f5950507f595050115c5052">[email protected]</a>"], [2, "bar", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="03616271436162712d606c6e">[email protected]</a>"]]

To understand more about Object.values, check out: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Object/values

If you prefer using older versions like ES5, you can still accomplish the same result with Object.keys. It might be a bit longer but does the job effectively:

JSON.parse(dataCarrier).map(function(obj) {
    return Object.keys(obj).map(function (key) {
        return obj[key];
    });
});

*Source: How to get all properties values of a Javascript Object (without knowing the keys)?

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

What's the best way to ensure that all the numbers I input into my calculator app are effectively combined when I press the buttons?

For my very first coding project, I decided to create a calculator app. Despite the abundance of tutorials available online, I wanted to challenge myself by breaking down the problem into smaller steps on my own. However, I've encountered an issue wh ...

Instructions for transferring a JavaScript array to a Java servlet

Greetings everyone! I am currently working on a web application with an orthodox approach, utilizing AJAX in Java and JavaScript. I am wondering if it is feasible to pass an array from JavaScript to a Servlet. ...

Aggregate SQL data using JSON arrays

I am currently developing a webpage designed for educators, showcasing students' test performance results. To visually represent the data, I am incorporating the Highcharts JavaScript library. At this stage, I have a PHP script utilizing PDO to gene ...

PHP AJAX Serial Port Text Input Command

Recently, I've been delving into the world of PHP and AJAX. Despite being a newcomer, I've managed to grasp some basic concepts over the past few weeks. Along the way, I've relied on various posts from this platform for guidance, so when a p ...

Guide on streamlining interface initialization within a React project using Typescript

Working on my Typescript project, I consistently utilize an interface within the State of various components: interface Item { selectedValue: string originalSelectedValue: string loading: boolean disabled: boolean isValid?: boolean } ...

Guide on setting up JSME, a chemistry portal integrated with JavaScript, within vuejs

I am looking to integrate the JSME chemistry portal into my Vuejs application. Upon the initial page load, an error is displayed: JSME initialization error: HTML id jsme_container not found. Strangely, upon refreshing the page, the error disappears. How ...

Discovering the length of the longest contiguous subarray with a sum that is evenly divided by a specific number

I am seeking a method to find the longest continuous subarray whose sum is divisible by a given number 'k'. I have already implemented a brute-force approach with a time complexity of o(n^2). However, I now wish to achieve this in o(n) time. Can ...

Is it possible to convert an index array into a mask array using Numpy?

Can you transform an array of indices into an array of zeros and ones within a specific range? For example, converting [2,3] to [0, 0, 1, 1, 0] within a range of 5. I am looking to create a process like this: >>> index_array = np.arange(200,300) ...

testing express router with several different handlers

I have been testing my guard middleware and everything appears to be functioning correctly, but my expect statement is failing. /// auth.test.js const request = require('supertest'); const express = require('express'); const app = req ...

Error in PHP upload process due to absence of data in $_FILES array

I'm encountering a common issue with PHP: The $_FILES array is empty when files are too large. Here's my php.ini configuration: max_execution_time = 300000 max_input_time = 600000000 memory_limit = 5100MB post_max_size = 5000MB upload_max_files ...

Navigating complex JSON structures in Go Lang

Dealing with a messy block of JSON can be quite a task, especially when you need to read and modify values that are deeply nested within. In my case, I specifically want to target two values designated by "I want this!" using Go. The challenge arises from ...

How to send arguments to a callback function in Next.JS

Here's the code snippet I'm working with: import Router from "next/router"; import React from "react"; export default function MainIndex() { return (<React.Fragment> <h1>Main Index Page</h1> ...

What is the best way to clear an array of messages using .subscribe in JavaScript?

Within my messages.component.ts file, I have the following code snippet: constructor(public messagesService: MessagesService) { this.subscription = this.messagesService.getMessage().subscribe(message => { this.messages.push(message); }); this.su ...

It seems like the method has already been executed despite encountering an unexpected end of JSON input error

Currently, I am utilizing the etherscan API to retrieve logs for certain events. Although my JSON parsing method seems quite traditional, an error is being thrown stating "unexpected end of JSON". function getEventHistory() { const topic0 = web3.util ...

tips for converting objects into arrays with JavaScript

I have an object and I would like to convert it into an array const object1 = { a: { hide:true}, b:{} }; I am currently using Object.entries to perform the conversion, however, I am struggling with understanding how it should be done. Object.entries ...

What are the steps to reduce the node version?

How can I downgrade my npm version from 16.13.1 to 12.0.1? Any guidance would be greatly appreciated! Thank you in advance. ...

JQuery error displaying [object Object]

I'm currently working on a calendar project where I have created a page to display events scheduled for a specific day. To ensure a seamless user experience without the need to reload the page every time a new event is added, I am utilizing Ajax. Us ...

What could be the significance behind these sudden pop-ups of console error messages?

var sendTitle = function() { var title = $("input[name='movie-search-title']").val(); getMovie(title) getQuotes(title) } $("input[name='movie-search-title']").keydown(function(e) { if (e.keyCode == 13) { e.preventDefault(); ...

Extensive Ajax requests are hindering brief Ajax status updates

I am currently running an ASP.NET MVC application on IIS with two main handlers, /DoWork (which takes about 10 minutes to complete) and /ReportStatus (which takes less than a second). The purpose of DoWork is to perform a task while ReportStatus provides u ...

Is the MUI Drawer Open 20% of the Time?

One issue I'm facing is with my MUI drawer - it's supposed to close after a menu item is clicked, but sometimes, about 1 out of 5 times, it remains open. I have based my current code on a helpful post on Stack Overflow. Take a look at the code s ...