Array object consisting of key value pairs

data = [
    [
      {
        key: 'test1',
        value: '0'
      }
    ],
    [
      {
        key: 'test2',
        value: '0'
      },
      {
        key: 'test3',
        value: '0'
      }
    ]
  ];

I need to transform it into the desired format shown below:

formattedData =
[{
 'test1':'0',
},
{
 'test2':'0',
 'test3':'0'
}]

I attempted to tackle this issue with the following code but couldn't succeed. Can anyone assist me in solving this problem? Thank you.

let formattedData = []
let counter = 0
for(let item of this.data){
 
  for(let prop of item){
   formattedData[counter].push(prop.key:prop.value)
  }
  counter++;
}

Answer №1

To accomplish this, you can utilize a combination of map and reduce:

const data = [
    [
      {
        name: 'item1',
        count: '0'
      }
    ],
    [
      {
        name: 'item2',
        count: '0'
      },
      {
        name: 'item3',
        count: '0'
      }
    ]
  ];
  
const transformedData = data.map(i =>  i.reduce( (acc,x) => ({...acc,[x.name]:x.count}),{}));

console.log(transformedData);

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

NextJS function utilizes its own references within React and automatically fetches data without the need for an import

I recently purchased this template and I'm trying to figure out which page the code snippet "{getLayout(<Component {...pageProps} />)}" is directed to during the initial load. It seems like it might be a global variable hidden somewher ...

Choosing from a list in Angular

I'm trying to make a dropdown menu that shows options in the format "code-description", but only displays the "code" portion when an option is selected. For example, showing "A-Apple" in the dropdown, but displaying only "A" when chosen. I am able to ...

Retrieving the value from the series object and showing it in the tooltip of a high chart with the help of Angular 4

I have successfully implemented the display of x and y values in the tooltip of a Highchart within my Angular 4 application. By utilizing the formatter function of the tooltip, I am able to achieve this functionality. The graphdata array is initially set w ...

Despite the presence of a producer and topic, sending Kafka messages is proving to be a challenge

Currently, I am using TypeScript and the KafkaJS library on my local machine with a single Kafka broker. After successfully connecting a producer, confirming the creation of my topic, and creating messages like so: const changeMessage = { key: id, ...

warning TS2322: Cannot assign type 'PropUser | null' to type 'PropUser'

Issue: Error: src/app/user/containers/shell-user-profile/shell-user-profile.component.html:1:20 - error TS2322: Type 'PropUser | null' is not assignable to type 'PropUser'. Type 'null' is not assignable to type 'Pro ...

Encountering a type error in Typescript when assigning a transition component to a Material UI Snackbar

Attempting to implement snackbar alert messages using Material UI in a React JS application with TypeScript. Encountering a type error when trying to modify the transition direction of the snackbar. Referenced the snackbar demo from Material UI documentat ...

Ways to test the reloading of window.location in angular 12 unit testing?

One of the functions in my Angular project is: reloadPage(): void { window.location.reload(); } Whenever I need to reload the page, I used to call this function. Now, I'm attempting to implement unit testing for this function, but it's not wo ...

I'm curious about the correct method for updating a parent component using a shared service within the ngOnInit function in Angular version 13

There have been instances where I encountered a scenario multiple times, where I utilize a shared service within the ngOnInit of a component to update a value in another component, specifically its parent. This often leads to the well-known Error: NG0100: ...

The absence of a scroll bar on the web application is preventing me from scrolling properly

The vertical scroll bar on my Angular app seems to have disappeared mysteriously. I haven't made any changes to the code recently, and I'm struggling to figure out why it's missing. I've spent days trying to troubleshoot this issue with ...

What is the method to insert a new <input> element after the last input field has been filled in

I recently started working on a form using StackBlitz, but I've hit a roadblock and need some guidance on how to proceed. My goal is to achieve a similar effect like the one shown in this gif: https://i.stack.imgur.com/76nsY.gif and I'd like to ...

At times, MomentJS may miscalculate and add an incorrect number of hours

My goal is to add a specific amount of hours to a 24-hour time, but I'm encountering an issue with the time 00:00. The code I've written works correctly for all times except midnight. For example, if I have 01:30 and add 1 hour, it gives me 02:3 ...

Sending file URL to Angular component

Hey there, I am looking to relocate an existing link within my Angular 4 project. For instance, the link I want to move is "". I have attempted to do so in my router configurations: path: 'test', component: TestComponent, children: ...

The characteristics of property 'X' do not align

I have a challenge that I am currently working on. I am creating an addIdToAnimal function that will take any type of Animal and assign an id to it. Every animal object has an attribute called animalType, which is defined as an enum. My main inquiries ar ...

Convert checkbox choices to strings stored in an array within an object

I have a intricate object structure JSON{ alpha{ array1[ obj1{}, obj2{} ] } } In addition to array1, I need to include another array: array2 that will only consist of strin ...

Angular: Merge two Observables to create a single list and fetch the combined data

I am currently working on creating a function that returns an observable with a list, compiled from several observables. I feel like I am very close to finding the solution because the debugger stops right before displaying the list. Here is my code: ts t ...

Navigating through tslint: adhere to the one-variable-per-declaration rule

What is the best way to write code following this rule? let exampleArray = [...]; for (let j = 0, k = exampleArray.length; j < k; j++) { ... } ...

Using Angular 2+ to make HTTP POST requests and interact with the GDrive API. Implementing resumable file uploads

I am currently facing a challenge with uploading files to Google Drive using Angular 2. I have managed to upload files successfully, but they end up being labeled as "Untitled" without any title. Below is the code snippet I am using for the upload process ...

Error with Angular 5 Cross-Origin Resource Sharing

I am new to Angular development and here is the code I have written: export class FaceProfilComponent implements OnInit { domparser = new DOMParser(); doc: HTMLDocument; element: any; constructor(private http: HttpClient) {} get ...

What is the process for activating focus on an input element within a mat-select component?

How can I activate the cursor on the HTML input element (search field) using a keyboard inside mat-select? It functions properly when using a mouse, but in order to meet WCAG requirements, it needs to be fully functional with keyboard navigation. Click h ...

Show pictures stored in S3

I currently have an Amazon AWS S3 Bucket where I store images. Each object in the bucket has its own link, but when I try to open it in a browser, the image downloads instead of displaying directly on the site. This makes it challenging to view the images ...