Tips on transforming the array of objects (changing from its original form to a new form) using TypeScript

I have an array of objects containing data in a key-value format. Here is an example:

"data": [
    {
      "groupBy": "InvalidAuth",
      "count": 41
    },
    {
      "groupBy": "InvalidAuthEmpty",
      "count": 75
    },
    {
      "groupBy": "InvalidAuthSQL",
      "count": 75
    },
    {
      "groupBy": "Unsecured",
      "count": 75
    }
  ]

I want to transform this data into the following format, where "count" is renamed as "value" and "groupBy" is renamed as "name". How can I achieve this programmatically using TypeScript or JavaScript?

data:[
            {value:41, name:'InvalidAuth'},
            {value:75, name:'InvalidAuthEmpty'},
            {value:75, name:'InvalidAuthSQL'},
            {value:75, name:'Unsecured'}
]

The original format does not work with e-charts, as it only accepts data in the value-name form.

Can someone assist me with this conversion?

Thank you.

Answer №1

You can easily utilize the map function along with destructuring

const info = [{"category": "InvalidAuth","quantity": 41},{"category": "InvalidAuthEmpty","quantity": 75},{"category": "InvalidAuthSQL","quantity": 75},{"category": "Unsecured","quantity": 75}]
  
let result = info.map(({quantity:value,category:name}) => ({name,value}))

console.log(result)

Answer №2

To transform the original array and retrieve a new array with specific property names, you can utilize the map method:

const items = [
    {
      "category": "Electronics",
      "quantity": 10
    },
    {
      "category": "Clothing",
      "quantity": 20
    },
    {
      "category": "Books",
      "quantity": 15
    },
    {
      "category": "Home Decor",
      "quantity": 30
    }
  ];
  
  const modifiedItems = items.map(item => ({
    name: item.category,
    amount: item.quantity
  }));
  
  console.log(modifiedItems);

Answer №3

Perhaps this could be the solution you are seeking:

const updatedData = [];
data.forEach((item) => {
  updatedData.push({
    value: item.count,
    name: item.groupBy,
  });
});

Answer №4

To complete the task, simply loop through the data array, renaming existing keys and removing old ones.

var data= [
    {
      "groupBy": "InvalidAuth",
      "count": 41
    },
    {
      "groupBy": "InvalidAuthEmpty",
      "count": 75
    },
    {
      "groupBy": "InvalidAuthSQL",
      "count": 75
    },
    {
      "groupBy": "Unsecured",
      "count": 75
    }
  ]
  
   data.forEach(function(elem){
    elem.name =elem.groupBy;
    elem.value =elem.count;
    delete elem['groupBy'];
    delete elem['count'];
  });
  console.log(data);

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

Change the date from Thu Jan 01 1970 01:00:00 GMT+010 to the format yyyy/mm/dd

Currently, I am developing a web application using Angular which includes a form with a date field that utilizes the angular material datepicker component. Once a user selects a date from the datepicker, the retrieved value is in the format: Thu Jan 01 197 ...

Unable to transfer an array from getStaticProps method in Next.js

Whenever I pass a JSON array from getStaticProps in Next.js, I encounter this specific error message when trying to access it. TypeError: Cannot read property 'contentBody' of undefined module.exports../pages/[author]/[article].js.__webpack_expo ...

When attempting to parse a single string stored in a cookie with JSON.parse, it results in a "SyntaxError: Unexpected Number" error being thrown

I am facing an issue with parsing a string stored in a cookie. "d967fac49ef2466239168bbbde0a8d755a27ba81$[[\"__json_message\"\05425\054\"This is a message.\"]]" Also known as "\"d967fac49ef2466239168bbbde0a8d755a27ba81 ...

There was a failure to retrieve any data when trying to send an ajax request to

When attempting to send JSON data to my PHP, I am not receiving any response when accessing it in my PHP code. Below is the Ajax request being made: var project = {project:"A"}; var dataPost = JSON.stringify(project); $.ajax({ url: 'fetchDate.p ...

How can I send data with ajax and then navigate to the page with the posted information?

I'm facing an issue where I need to send 2 Ajax requests simultaneously. The challenge is posting data to one file, receiving a response, and then posting to another page with the intention of accessing the posted values using $_post on the next page ...

Interacting with a JavaScript button using C# WebBrowser

Can someone please assist me with a problem I'm facing? I have a webpage coded in HTML and Javascript. Whenever I use webBrowser1.Document.GetElementById("hmenu").InvokeMember("click");, the menu pops up on my screen. However, I am unsure how to cli ...

Is there a way to make a class method accessible in V8?

How can I make a class method accessible in a V8 context? I am trying to achieve something like the line below, but it's not working because lambda with captures cannot be treated as a function pointer. Global()->Set("foo",v8::FunctionTemplate::N ...

Field types: Elements encased within square brackets

When using Flow Types: export type GroupType = { options: OptionsType, [string]: any, }; What does the syntax [string]: any signify? Edit : Appreciate all the responses provided. How should I interpret this particular piece of code? import type { ...

What is the best way to include headers in a jQuery.load function similar to ajax requests

I've been struggling with this issue for a couple of days. I am trying to pass some header data in jQuery.load(). However, it seems that jQuery.load does not send headers like ajax does. Can anyone clarify whether sending headers is necessary in this ...

How can Javascript or Jquery determine the specific event assigned to an object?

Is it possible to retrieve the properties of HTML elements using their name or id? For example: document.getElementById('id').value; //Accessing element property in JavaScript $('#id').attr('class'); // Accessing correspond ...

What is the best way to arrange elements in my DOM if they are not being repeated in AngularJS?

I am currently working with a controller that contains two distinct controllers: one for the users model and one for the classes model. I want these sections to be displayed on top of each other based on the order in which they were opened. For example, i ...

The generic does not validate the types of two properties

type ComponentType = (...args: any) => any; type PlatformNotificationProps<TIcon extends ComponentType = ComponentType> = { component: TIcon; arg: Parameters<TIcon>[0]; }; const PlatformNotification = (props: PlatformNotificationProps) ...

Creating interactive functionality for textareas and input fields in Vue: A beginner's guide

I need assistance with creating a function where changing the input field will also automatically update the textarea's value. I have successfully implemented Vue js for updating the input field based on the textarea, but I am struggling to reverse th ...

The data in a NodeJS-generated JSON file is incorrect

In an attempt to generate a well-formatted JSON file containing the names of files (testfile1, testfile2, testfile3) located in a directory named "uploads," I wrote the code below: const fs = require("fs"); let toJson = {files: []}; let file = new Object() ...

Why is the responseText of an AJAX request empty on Chrome?

Why does this simple AJAX request work in IE but not Chrome? Check out the code below: var x = new XMLHttpRequest(); x.open("GET","style.php",true); x.send(); alert(x.responseText); The last line triggers an empty 'alert' window. Here's ...

What is preventing TypeScript from identifying the type of a parent based on its child?

Take a moment to explore the following example: type Num = { type: 'NUMBER' numberValue: number } type Str = { type: 'STRING', stringValue: string } type B_Num = { a: Num; numberData: number; } type B_Str = { ...

JavaScript forEach: alter items

I am facing an issue with using the forEach method on an array. Despite it being a mutator, it is not mutating the values in the original array as expected. Can anyone help me figure out what could be causing this problem? let array = [1, 2, 3, 4]; //de ...

What could be causing my nested child component to fail to display the content?

My current setup includes: Vue 2.5.16 Veux Vue router I have created a simple router view that searches for a child component within a parent component using the URL structure: /folders/parent-uuid/child-uuid Below is the code for the parent component ...

The double click functionality does not seem to be functioning within the Backbone View

I am trying to detect double click event within a Backbone view var HomePage = Backbone.View.extend({ initialize: function(){ this.render(); }, render: function(){ var template = _.template($('#app1').html()); ...

Angular error TS2322 arises when attempting to assign a type of 'Observable<{}>' with the share() operator

Currently diving into Angular 5, I've been exploring the Observable/Observer pattern to facilitate event sharing and data changes among subscribers. Below is a snippet of the code in question: ... @Injectable() export class NidoService { ... eve ...