Structure an object to divide the header of the information

Recently, I've been working on a Typescript project where I encountered the need to reformat a JSON object. The original object consists of an array of objects with keys and corresponding values. My goal is to separate the keys into one array and the data into separate arrays.

Here is the current structure of the object:

[
  {
    "id": "1",
    "ser": null,
    "IP": null,
    "host": "",
    "type": "Web",
    "auth": ""
  },
  {
    "id": "2",
    "ser": null,
    "IP": "191.174.230.02",
    "host": "",
    "type": "Proxy",
    "auth": ""
  }
]

This is the desired outcome:

[
    "id",
    "ser",
    "IP",
    "host",
    "type",
    "auth"
],
[
    "1",
    null,
    null,
    "",
    "Web",
    ""
],
[
    "2",
    null,
    "191.174.230.02",
    "",
    "Proxy",
    ""
]

To achieve this structure, I intend to introduce a new property called values in the object:

{
  "values": [
    [
        "id",
        "ser",
        "IP",
        "host",
        "type",
        "auth"
    ],
    [
        "1",
        null,
        null,
        "",
        "Web",
        ""
    ],
    [
        "2",
        null,
        "191.174.230.02",
        "",
        "Proxy",
        ""
    ]
  ]
}

Answer â„–1

  1. Retrieve the keys of the first element by using Object.keys(data[0])
  2. Iterate through all elements with Object.values(element) to access each element's data
  3. Add both the key and element value to an array

Check out the code snippet below for implementation:


    var data = [
      {
        id: "1",
        ser: null,
        IP: null,
        host: "",
        type: "Web",
        auth: "",
      },
      {
        id: "2",
        ser: null,
        IP: "191.174.230.02",
        host: "",
        type: "Proxy",
        auth: "",
      },
    ];

    var arr = [Object.keys(data[0])];
    for (let element of data) {
      arr.push(Object.values(element));
    }

    var obj = { values: arr };
  

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

Iterating through multiple arrays to find the smallest neighboring element and storing it in a variable

Let's simplify the scenario for this question: I have four arranged arrays, named a, b, c, and d. Each array contains integers ranging from 1 to 1000. The objective is to iterate through them in ascending order of integers. For instance, if a = [3, ...

Showcasing JSON information within a dropdown menu

In my project, I am working with two different JSON files named contacts and workers. Currently, I am using *ngFor to display the name of the contacts. In addition, I am also displaying the assigned workers for each contact in a dropdown, as shown below: ...

Incorporate interactive elements into the form

I'm facing an issue with adding 2 dynamic input fields to my form. <div formArrayName="details"> <div *ngFor="let detail of _detailRowNumber; index as i"> <mat-form-field appearance="fill"> & ...

Creating shared VB array initializers for the NerdDinner application can be done by following these steps

Currently, I am working my way through the NerdDinner tutorial, where I am converting it to VB as part of my exercise. I have just passed the C# Yield statement but now I am facing a challenge with Shared VB Array Initializers. static IDictionary<strin ...

The JObject parser abruptly halts its execution without producing any results or indicating any errors

I have been attempting to retrieve and parse a JSON response from a webapi using the following code: var pemail = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="44302b2a3d37042329252d286a272b29">[email protected]</ ...

Error message: Attempting to call the row() function on a variable that is not an object while trying to

Currently, I am using CodeIgniter for my application development and incorporating jQuery to transmit JSON data. Below is the code snippet: public function updateRequest($id_request, $jenis_request, $keluhan ){ $data= array( 'jenis_r ...

What steps should I take to generate a compiler error when a variable is not of the type "never"?

Imagine having a set of conditions with different possible values and wanting to cover each potential case. In the event of adding a new condition in the future but forgetting to handle it, it is important to have an error detection mechanism—ideally cat ...

Accessing location information using jQuery from Google's Geocoding API

Recently, I've been delving into the realm of Google Maps Geocoding and attempting to comprehend how to decipher the JSON data that it transmits back. This snippet showcases what Google's response looks like: { "results" : [ { ...

Angular button press

Recently, I started learning Angular and came across a challenge that I need help with. Here is the scenario: <button *ngIf="entryControlEnabled && !gateOpen" class="bottomButton red" (click)="openGate()">Open</button> <button *ngIf ...

Is there a tool in VS Code that offers a unique editor specifically designed for managing package.json files?

As I work on my small VS Code extension, I'm realizing that the package.json file is getting quite big and hard to manage. Are there any VS Code extensions that offer a more user-friendly editor for package.json? I came across the Json Editor, but I&a ...

What is the method for assigning a string to module variable definitions?

As someone new to TypeScript and MVC, I find myself unsure if I am even asking the right questions. I have multiple TypeScript files with identical functionality that are used across various search screens. My goal is to consolidate these into a single fil ...

Developing a Library for Managing APIs in TypeScript

I'm currently struggling to figure out how to code this API wrapper library. I want to create a wrapper API library for a client that allows them to easily instantiate the lib with a basePath and access namespaced objects/classes with methods that cal ...

Begin with the constant element within the array initialization

What is the reason for the compiler (VC++) disallowing (error C2975) const int HASH[] = {24593, 49157}; bitset<HASH[0]> k; and how can I resolve this issue (initializing templates with constant values from an array)? ...

The front and back elements display only the elements that have been added most recently, excluding the first and last elements added

During my college days, I faced challenges in grasping DSA concepts and now I am determined to learn it independently. As part of my learning process, I am developing a simple application where users can make reservations that are then inserted into a queu ...

Merge the elements of one array with the elements of another array simultaneously

Can a function be created that combines each value from two arrays, even if the arrays are of different lengths? For example: arr1 = ["apple", "banana", "cherry"]; arr2 = ["pear", "kiwi", "orange"] mergedArr= ["applepear", "applekiwi", "appleorange", " ...

Encountered a problem while attempting to post in Angular, receiving an error message stating "net::ERR

I recently started learning Nodejs. I've created an API on a local server using Mysql and I'm working on the frontend with Angular, while using Nodejs and Express as the backend. However, I'm facing an issue where my Angular app cannot conne ...

Error in Twitter Client due to JSON Exception

Currently, I am developing a Twitter Client app for Android by following a tutorial. However, after going through the authorization process in the application, it only shows an error message saying "JSON Exception" without displaying any timeline. Below i ...

I'm trying to convert the object values into an Array in Angular 8 - any suggestions on how to

I have a set of object values that I need to convert into an array format. var data =[ { "project": "Sciera Internal Application", "hours": { "DATA SCIENCE": 3270, "DEVELOPMENT": 2895 ...

What exactly is [index-1] contributing to the solution? Can you explain in simple terms?

As a newcomer to Python, I am currently working on an Exercism exercise. In addition to this being my first time working with matrices, I have been learning a lot over the past couple of weeks. While I am still getting the hang of Classes in Python, the ...

What are the best ways to utilize props in connection with this information?

It seems that I have no data on videos but there is data on clients. I suspect that my fallback isn't working because of this. Is there a way to separate these data sets so I can implement something like this with the fallback: if(!videos) return pro ...