A guide to compacting JSON data in Typescript or Angular: A step-by

Looking for help with formatting JSON in Typescript or JavaScript. Which approach would be better?

var data = {
"value 1" : [
    {
        type : String,
        Dicription : "abc"
    },
    {
        type : int,
        Dicription : "xyz"
    },
    {
        type : String,
        Dicription : "pqr"
    },
    ]
"value 2" : [
    {
        type : String,
        Dicription : "abc"
    }
    ]
"value 3" : [
    {
        type : String,
        Dicription : "abc"
    },
    {
        type : int,
        Dicription : "xyz"
    }
}

Desired Output:

{
    {
       value : value1,
       type : String,
       Description : "abc"
    },
    {
       value : value1,
       type : int,
       Dicription : "xyz"
    },
    {
       value : value1,
       type : String,
       Dicription : "pqr"
    },
    {
        value : value2,
        type : String,
        Description : "abc"
    },
    {
        value : value3,
        type : String,
        Description : "abc"
    },
    {   
        value : value3,
        type : int,
        Description : "xyz"
    }
}

I attempted to iterate through the data but couldn't achieve the desired output. I tried to flatten it, but got objects like {value : value, {type: String, Description : abc}}. Any suggestions on how to solve this?

Answer №1

To transform the object into an array, use the Object.entries() method and then map the entries to create an array of objects:

const result = Object.entries(data) // retrieve the object's key-value pairs
  .flatMap(([key, value]) =>  // map and flatten the sub-arrays
    value.map(obj => ({ // map each sub-array and merge with the key
      key,
      ...obj
    }))
  )

Answer №2

In order to tackle the problem, I separate the keys and values and then loop through the first object to create a new object where I store the values.

Here is how I approached the solution:

var keys = Object.keys(data);
var values = Object.values(data);
var length = Object.values(data).length;
keys.forEach(function (key, index){
  values.forEach(function (obj, i) {
    if(index == i){
      var innerValue = Object.values(obj);
      for(i=0 ; i<=innerValue.length; i++)
       {
        new.push({
          'value': key,
          'type': innerValue[i].type,
          'Description': innerValue[i].abc,
         });
       }
     }
   });
});

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 can I retrieve a Long Integer and store it in a Byte Array using VBA

Does anyone know how to generate a random Long Int number (4 bytes) and store it in the last 4 bytes of a byte array (byte array defined as Dim MybyteArray(1 to 16) As Byte)? I've been struggling to find a straightforward solution for this. Any sugges ...

What is the best way to start an array with each element running on its own thread?

My goal is to generate an array of size n based on user input, with each element set to 1 in separate threads when the program is executed. Here's what I have accomplished so far: #include <windows.h> #include <stdlib.h> #include <stri ...

Can tap and drag on mobile devices be accurately detected?

I'm wondering if it's possible to identify when a mobile user is performing a tap and drag using javascript or jquery. I've encountered an issue where ripple effects are triggered on elements while users are tapping and dragging/browsing con ...

Establish a connection to the ActiveMQ broker utilizing STOMP protocol in an Ionic application

I've recently received an Ionic + Capacitor app that is primarily meant to run on the Android platform. My current task is to incorporate communication with a remote ActiveMQ broker into the app. To achieve this, I utilized the STOMP JS library which ...

Execute the cucumber cli programmatically in the index.js file of a node application

Recently, I received an automation framework built in CucumberJS and Node with Selenium. However, the framework is using an outdated version of Cucumber that relies on promises. Wanting to take advantage of the latest synchronous step feature, I decided to ...

The NestJS HttpService is encountering issues with API calls when an Interceptor is implemented

When using NestJS API App with HttpService to call another API, the functionality works successfully without any custom interceptors. However, the issue arises when attempting to view the response from the called API. The following code snippet showcases ...

Insert a comment prior to a function with the TypeScript Compiler API

I have a TypeScript file that needs to be transpiled into JavaScript. As part of this conversion process, I want to include a comment before every function using the TypeScript Compiler API. I experimented with two different methods. One involved accessin ...

Failure in converting a JSON file to a QR-Code

I am attempting to utilize pyqrcode to convert a json file into a qr code import tkinter as tk from tkinter import filedialog import json import pyqrcode as qrcode root= tk.Tk() root.title('JSON File to QR Code Converter') canvas1 = tk.Canvas(r ...

Is there a "hasContent" function available in webdriverjs?

Currently, I am exploring the use of webdriverjs for testing purposes and I am really enjoying the experience so far. However, I have encountered a challenge while attempting to run more general tests. I am wondering if there is a way to check if a webpage ...

Creating a wrapper component to enhance an existing component in Vue - A step-by-step guide

Currently, I am utilizing quasar in one of my projects. The dialog component I am using is becoming redundant in multiple instances, so I am planning to create a dialog wrapper component named my-dialog. my-dialog.vue <template> <q-dialog v-bin ...

Incorporating a discreet progress bar into traditional file uploading processes

Have you noticed the trend of new, advanced file uploaders, many of which are Flash-based like SWFUpload? These uploaders can display a progress bar while files are being uploaded, making it much easier for users with shaky or low-bandwidth connections. H ...

Changing a string into a multi-dimensional array using javascript

The following data is retrieved from the REST API: [[5671, 204], [5673, 192], [5674, 120], [5683, 120], [5684, 192], [5685, 204]] When using typeof in JavaScript on the above, it returns a string. To convert it to a multi-dimensional array: <script ty ...

Issue with mouse movement in Selenium and Protractor not functioning as expected

Greetings! I am currently facing an issue in my Angular application with Openlayers3 map integration. There is a layer representing a building on the map, and when I try to click on a building during testing, it should trigger a side panel displaying image ...

Using Vue.js data with an erb link_to tag

Currently, I am developing a Rails application where one page utilizes Vue.js to load a Google map, make some API calls with Axios, and gather user values using Vue.js. My goal is to pass these values as parameters within a "link_to" erb tag. Please refer ...

Ways to customize the Angular Form Directive for universal autocomplete="off" functionality

One interesting aspect of Angular is that the <form> directive can be extended. I'm curious to know if there's a way to do this effectively. The reason behind my inquiry is that I desire to automatically add the attribute autocomplete="off ...

How can I correctly parse JSON data?

I am looking to parse JSON data with a specific format [{"buyer":"EcUx5JGHhJ9Y4qR6HR8TDHqi5QC3MNNqHf1dbGdHyaxW","count":1,"foxy":false,"id":276870,"mint":"SH1f6At4pScGi42Xfp6tvf9eKirfMd5bi2oPmxdpUAF","price":2700000000.0,"seller":"wxo1Rj8JAy52FhhqTSiPTNbG ...

Limit the length of long strings in JSON using Python

Provided with a JSON object [ { "default_value": "True", "feature_name": "feature_1", "active_on": "remote_1,remote_2,remote_3,remote_4,remote_5,remote_6,remote_7" ...

Guide to integrating a Custom Font into live data on a PDF file with the help of jsPDF

I recently successfully converted a dynamic webpage to PDF using jsPDF and now I'm looking to customize the font family of the PDF document. Is there an option for this in jsPDF? Please advise, thank you! Here is my code snippet: <div id="#p ...

How to properly pass data between parent and child components in VueJS without using provide/inject

I've been experimenting with using provide and inject to pass data from parent to child elements, but I'm running into an issue where the data isn't available in the child element. It's strange because when I add the same data directly ...

Leveraging node.js to power mobile applications along with an administration panel built using angular

Our current setup involves a mobile app that communicates with some APIs (no backend yet). I'm considering using node.js as a service for these APIs, even though I've never used it before being primarily a .net developer. For the administrative ...