convert a JSON object into an array field

I am looking to convert a list of objects with the following structure:

{
    "idActivite": 1,
    "nomActivite": "Accueil des participants autour d’un café viennoiseries",
    "descriptionActivite": "",
    "lieuActivite": "",
    "typeActivite": "",
    "horaireDebActivite": 1512028800,
    "horaireFinActivite": 1512059388,
    "horaireDebSession": 1512030600,
    "horaireFinSession": 1512318588,
    "nomSession": "",
    "isInSession": false
}

to another format like this:

[
    "idActivite": 1,
    "nomActivite": "Accueil des participants autour d’un café viennoiseries",
    "descriptionActivite": "",
    "lieuActivite": "",
    "typeActivite": "",
    "horaireDebActivite": 1512028800,
    "horaireFinActivite": 1512059388,
    "horaireDebSession": 1512030600,
    "horaireFinSession": 1512318588,
    "nomSession": "",
    "isInSession": false
]

using TypeScript 2.5.

Answer №1

Although both concepts may seem similar, it is important to note that they are fundamentally different in nature. An array is a collection of elements accessed by numerical index, while the structure described in your example utilizes string-based indexes and thus falls under the category of objects according to the JSON specification. If you encounter difficulties iterating through such a structure, consider using the following code snippet:

for(var key in myObject){
  console.log(myObject[key]);
}

Answer №2

If you're looking to create an array in the format [ {key, value} ], you can use the following approach:

let exampleObject = { first: 1, second: 2 }
let newArray = []

for (const property in exampleObject) {
    newArray.push({ key: property, value: exampleObject[property] })
}

console.log(newArray)

This method maintains a linear scaling relationship with the size of the array being processed.

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

Determine the object ID of an element in the array at index x if you are already aware of the array[x]->ID

Suppose we have the following array from a previous question... How do I locate the [X]=> stdClass Object where the [id] of this object is [id] => 9??? Array ( [0] => stdClass Object ( [id] => 8 [book_catego ...

Utilize interface as a field type within a mongoose Schema

I am currently working with typescript and mongoose. I have defined an interface like this: interface Task { taskid: Boolean; description: Boolean; } My goal is to create a schema where one of the fields contains an array of Tasks: const employeeSche ...

In Python, I've encountered a problem when creating a dictionary by iterating over a list of items. The issue is that all the list items end up getting added to every object in my

I have been struggling with this issue for a while now, trying to find a simple solution. The problem arises when I iterate through a list of objects retrieved from a database (massiveList). My goal is to create a dictionary to be used as JSON for reportin ...

Collection<T> LINQ for JSON

I'm in the process of developing a Windows Phone app and utilizing JSON.NET for data processing. Consider this scenario: you require a List<myObject>. Rather than creating it directly, I opt to: IList<string> data1 = json["response"]. ...

Having trouble sending a JSON object from Typescript to a Web API endpoint via POST request

When attempting to pass a JSON Object from a TypeScript POST call to a Web API method, I have encountered an issue. Fiddler indicates that the object has been successfully converted into JSON with the Content-Type set as 'application/JSON'. Howev ...

What is the best way to retrieve information from a database using JSON with PHP, JQUERY, and

Trying to retrieve data from a MySQL database and pass it to a JavaScript file has been quite a challenge. Despite searching extensively online, the examples I found didn't work in my specific scenario. .html file <!DOCTYPE html PUBLIC '-//W ...

Difficulty encountered while duplicating NSMutableArray

My attempt to duplicate one array into another is causing an issue: NSMutableArray *itemsCopy = [[NSMutableArray alloc] initWithArray:self.items copyItems:YES]; Instead, I encounter the following error: *** Terminating app due to uncaught exception &apo ...

Angular 2: Harnessing the Power of Data-Binding with setTimeout

It appears there is an issue with changing a component's attribute inside a 'setTimeout' function during the initial page load. Consider having a component called 'HomeComponent' with the attribute: isValueTrue: boolean = false; ...

Issue with locating assets in Angular 6 build

Hey there! I'm currently facing an issue while trying to build my angular project. In the project, I am using scss with assets, and below is a snippet of how I have defined the background image: .ciao { background-image: url("../../assets/images/bc ...

Please ensure to close the dropdown menu once the function has been called

I'm encountering an issue with a dropdown menu. When I expand the dropdown menu, everything works as expected. However, is it possible to disable the first search button and the txtSearch input field (referring to the class "glyphicon glyphicon-search ...

`Searching for the perfect code: Collection of jTextField elements`

I've been searching everywhere online for a specific code snippet: JTextField[] jt = new JTextField{jTextField1,jTextField2,..}; Previously, I had this exact code saved on a hard drive in case I needed it again. Unfortunately, the hard drive failed ...

Experimenting with viewProvider in a component test

@Component({ selector: 'app-entity-details', templateUrl: './entity-details.component.html', styleUrls: ['./entity-details.component.scss'], viewProviders: [{ provide: ControlContainer, useFactory: (container: ...

Step-by-step guide to initializing a project using React with Typescript and a functional server-side script

I am working on a project that involves a React Typescript app (created using Create React App). In this project, I need to have an executable script that can run alongside the React app. Both the app and the script are intended to only run on local machin ...

Tips for ensuring that CSS hover effects stay in place even when the page is scrolled

i'm having trouble with a project in React JS that I received from another team. I'm not very confident in my skills with React JS, and I'm facing an issue where a certain part of the page is supposed to change to red when hovered over. Howe ...

Create an asynchronous method within an object-oriented programming (OOP) class

Presenting my Activity class. export class Activity { _name: string _goIn: boolean constructor(name: string) { this._name = name; this._goIn = false; } isGoIn() { return this._goIn; } setGoIn() { // instructions to asyn ...

Issue with sending headers in HttpClient.post method in Angular 8

I have successfully implemented the following code: this.http.post (TGT_IP,body, {responseType: 'arraybuffer'}).subscribe( (val) => { console.log("POST call successful value returned in body", val); ...

Checking radios or checkboxes will always result in a null value when retrieving their form values

After following the instructions in the Angular 2 cookbook for dynamic forms, I encountered an issue with the radios and checkboxes. Despite checking them, they always return a null value. Interestingly, the touched properties of the radios and checkboxes ...

Edit the JSON data within the Scrapy pipeline

How can I add all the data from a json/dictionary in a scrapy pipeline to a key at the beginning and remove the brackets? [ { "date":"2015-11-25", "threat_level_id":"1", "info":"TEST", "analysis":"0", "distribution":"0", "orgc":" ...

Unable to retrieve data from a nested object within a JSON structure

In my React project, I have created a function component like the one below: function FetchData() { const [randomUserData, setRandomUserData] = useState(''); const url = 'https://randomuser.me/api/'; const fetchData = () => { ...

Encountering issues when attempting to set up graphqlExpress due to type

This is my first experience using GraphQL with Express. I have created a schema: import { makeExecutableSchema } from "graphql-tools"; import { interfaces } from "inversify"; const schema = ` type Feature { id: Int! name: String ...