Creating a JSON structure using an array in Typescript

Here is an example of my array structure:

[
  {
    "detail": "item1",
    "status": "active",
    "data": "item1_data"
  },
  {
    "detail": "item2",
    "status": "inactive",
    "data": "item2_data"
  },
  {
    "detail": "item3",
    "status": "active",
    "data": "item3_data"
  },
  {
    "detail": "item4",
    "status": "inactive",
    "data": "item4_data"
  }
]

My goal is to transform the above array into this format:

{
  item1: item1_data,
  item2: item2_data,
  item3: item3_data,
  item4: item4_data
}

With a large number of objects in the source array and multiple arrays to work on, I am looking for the most efficient method using typescript. What approach would be best?

Answer №1

To simplify the process, you can create an interface to define the layout of your field definitions and then iterate through an array to add each field individually.

interface IFieldDefinition {
  key: string;
  value: string;
}

const fields: IFieldDefinition[] = [
  {
    "key": "field1",
    "value": "field1_value"
  },
  {
    "key": "field2",
    "value": "field2_value"
  },
  {
    "key": "field3",
    "value": "field3_value"
  },
  {
    "key": "field4",
    "value": "field4_value"
  },
  {
    "key": "field5",
    "value": "field5_value"
  }
];

const resultObject: Record<string, string> = {};

for (const field of fields) {
  resultObject[field.key] = field.value;
}

Answer №2

Here's a sample code snippet:

const exampleJSON = [
  {
    "key": "value1",
    "action": "perform",
    "result": "success"
  },
  {
    "key": "value2",
    "action": "execute",
    "result": "failure"
  },
  {
    "key": "value3",
    "action": "complete",
    "result": "error"
  }
]

JSON.parse(exampleJSON)

const newObj = {}

for (let j in exampleJSON) {
  const prop = exampleJSON[j].key
  const val = exampleJSON[j].result
  newObj[prop] = val
}

JSON.stringify(newObj)

Using a for loop is preferred in this scenario due to its efficiency with large datasets, as opposed to methods like forEach.

This solution is written in JavaScript, but TypeScript would involve similar logic.

Answer №3

clever one-liner

const convertJsonToArray = (arr: Object[]) => {
    return Object.fromEntries(arr.map(item => [item["key"], item["value"]]));
}

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

Issues with updating values in Angular form controls are not being resolved even with the use of [formControl].valueChanges

[formControl].valueChanges is not triggering .html <span>Test</span> <input type="number" [formControl]="testForm"> .ts testData: EventEmitter<any> = new EventEmitter<any>(); testForm: FromCo ...

Establishing a secondary Node.js service for local communication with Parse Server

My current project involves using Node.js + Parse Server for an application. I have been utilizing the Parse SDK from the client side, but there are still many changes and refactors that need to be made. One issue I am facing is that certain logic should b ...

Converting group by values into JSON in Django is a common task that can be achieved by

Currently, I am facing an issue while trying to convert my grouped data into JsonResponse in Django. The error message that keeps popping up is: AttributeError: 'dict' object has no attribute 'f_type' This function below is responsi ...

Transforming localhost into a server name in a Node.js environment

Recently I began working on full stack development. I have a physical server and I want to upload my code to it so I can run the NodeJS server from there. This way, when people try to access my site, they will use or instead of localhost:port, which on ...

There seems to be a problem with the sorting functionality on the table in React JS,

My React table is functioning well with all columns except for the country name column. I double-checked the API and everything seems to be in order, but I'm stuck on how to troubleshoot this issue. const Table = () => { const[country, setCount ...

Implementing a Reset Button to Clear Checkboxes with PHP or JavaScript

I'm looking for help with setting up a button to reset the checkboxes on my preferences page. UPDATEL: Here's more information: The solutions provided should only affect checkboxes that are currently selected, not those enabled onLoad. This is ...

Exploring the differences between two CSS style attributes using JQuery

Can someone help me with a quick question about CSS? I need to compare two style attributes, specifically margin-left. If the margin-left is less than 500px, I don't want to make any changes. However, if it's greater than 500px, I want to add ano ...

Interactive navigation through scrolling with PHP onchange event

I need help with a PHP-related issue. I have a list of products that are generated dynamically using PHP. When a user clicks on one of the items in the list, the products are sorted. I also want the user to be smoothly scrolled to a new section of the page ...

Response is sent by Sequelize Foreach loop before data is updated

My goal is to retrieve all content and media from a post, then append it to a new post before sending it as a response for easier access to the data. The issue I'm encountering is that the response is being sent before the content and media are fetche ...

The absence of a defined window - react-draft-wysiwyg integration with Next.js (SSR) is causing issues

Currently, I am in the process of developing a rich text editor that is used to convert plain HTML into editor content using Next.js for SSR. While working on this project, I encountered an error stating "window is not defined," prompting me to search for ...

Retrieving information from a JSON API using Angular with Typescript

Currently, I am dealing with an API JSON to fetch a list of countries, followed by a list of states, and then cities within that state and country. The challenge lies in the second API call that I make. In the beginning, I load a list of continents and the ...

Bring in a library with Angular2 using webpack

I am currently utilizing the angular2-webpack starter from GitHub, and I am looking to incorporate an npm library, such as Babylon JS. My approach so far has been as follows: import * as BABYLON from 'babylonjs/babylon'; The Babylon library inc ...

Revitalize website when submitting in React.js

I need assistance with reloading my React.js page after clicking the submit button. The purpose of this is to update the displayed data by fetching new entries from the database. import React, {useEffect, useState} from 'react'; import axios from ...

Observables and the categorization of response data

Understanding Observables can be a bit tricky for me at times, leading to some confusion. Let's say we are subscribing to getData in order to retrieve JSON data asynchronously: this.getData(id) .subscribe(res => { console.log(data.ite ...

Utilizing two imports within the map() method

I have been considering the idea of incorporating two imports within map() in my React code. This is how my code looks: {this.state.dataExample.map(item => ( <ItemsSection nameSection={item.name} /> item.dat ...

Angular promise not triggering loop creation

I am encountering an issue with a particular function handleFileInput(file: any) { let promise = new Promise((resolve, reject) => { this.uploadFileDetails.push({ filename:this.FileName,filetype:this.FileType}); ... resolve(dat ...

Is it possible to extract form data from a div tag based on its class name?

I'm working with some code that looks like this: var iconContainer = document.getElementById('iconContainer'); var icon = iconContainer.getElementsByClassName("item"); for (var i = 0; i < icon.length; i++) { icon[i].addEventListener ...

Creating a dynamic nested form in AngularJS by binding data to a model

Creating a nested form from a JSON object called formObject, I bind the values within the object itself. By recursively parsing the values, I extract the actual data, referred to as dataObject, upon submission. To view the dataObject in a linear format, r ...

Retrieving data from a JSON file at 10-minute intervals with Ajax and visualizing it on Google's globe API

After downloading Armsglobe, a globe API provided by Google to draw lines in countries using their names, I noticed that the original code does not fetch JSON data periodically. I attempted to use a simple setTimeout() function in dataloading.js to address ...

A TypeScript generic function designed to accept either two arrays or two objects, but not a combination of both

Currently, I am creating an extend function in TypeScript that has the capability to: Update the first object with the keys/values of the second when given two objects. Append the elements of the second array to the first array when provided with two arr ...