Change the format of the array from the initial array to the new array structure

I have a multi dimensional array that I need to convert into the array2 structure. I've tried various methods, but all of them have resulted in bulky code and lots of iteration. Is there an easier way to accomplish this task?

I am new to Angular and JavaScript.

var array1=[
        {
            "id": 1,
            "name": "Johny",
            "category": [
                {
                    "id": 12,
                    "name": "GUI",
                    "status": {
                        "id": 123,
                        "status": "working",
                        "name": "GUI"
                    }
                },
                // more nested objects here
            ]
        },
        // more arrays of objects here
    ]
    

I want to transform this array into array2.

var array2=[
        {
            "id": 1,
            "name": "Johny",
            "category": [
                {
                    "id": 12,
                    "name": "GUI",
                    "data": [
                        // transformed data structure
                    ]
                },
                // more transformed data structures
            ]
        },
        // more transformed arrays here
    ]
    

Output should be in the array2 structure. Thank you in advance.

Answer №1

If you're aiming to include the original data as an extra `data` attribute, you can achieve this easily by employing a `forEach()` iteration along with the map() method:

array1.forEach((object) => {
    object.category = object.category.map((category) => {
    return {id: category.id, name: category.name, data: category}
  });
})

Hopefully, this approach meets your requirements :-)

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

Jersey 2.2 excels at producing XML output smoothly, yet encounters difficulties when generating JSON

I'm facing a strange issue with my web services setup. I am using Jersey 2.2 for creating restful APIs, along with jersey-media-moxy. Strangely, when I produce output in application/xml format, everything works perfectly fine. However, if I try to pro ...

Can you explain the distinction between embeddedViewRef and templateRef?

check this page for more information The statement above explains how an embedded view can be accessed from a different component than the one where it is defined, or it can be created separately using a TemplateRef. Can you clarify what this means? I&ap ...

Angular 8: How to Filter an Array of Objects Using Multiple Conditions

I am faced with the following scenario where I need to filter an array of objects based on lineId, subFamily, and status. My current code successfully filters based on lineId, but now I also need to include a condition for subFamilyId. I have two specifi ...

How can I enhance speed and efficiency when transferring data into MySQL databases?

I am currently developing a website using Django and MySQL (MyISAM) as the backend. The database data is being imported from multiple XML files processed by an external script and output as a JSON file. Whenever a new JSON file differs from the previous on ...

Is it possible to generate objects dynamically as the program is running?

Looking at the code snippet below, I currently have an array containing two JSON objects. However, if I need to create 20 objects, is there a more efficient way than manually writing each object in the array? Furthermore, is it possible to generate these o ...

Definition of a class in Typescript when used as a property of an object

Currently working on a brief .d.ts for this library, but encountered an issue with the following: class Issuer { constructor(metadata) { // ... const self = this; Object.defineProperty(this, 'Client', { va ...

Utilizing Powershell to eliminate characters from a string

After pulling a list of IPs from a JSON file, I've been using the code snippet below: $Request = 'https://url-to-json.com/file.json' $AWSIPs = Invoke-WebRequest $Request | ConvertFrom-Json | Select-Object prefix -ExpandProperty prefixes -Ex ...

Tips for bringing in a text file within a NodeJS application using TypeScript and ts-node during development

I am currently developing a NodeJS/Express application using TypeScript, Nodemon, and ts-node. Within this project, there is a .txt file that contains lengthy text. My goal is to read the contents of this file and simply log it to the console in developmen ...

Issue with loading JSON library encountered in the Python-Twitter library

I have implemented the following code using Python 3.3 modules (installed via Pip3.3): import simplejson import httplib2 import twitter api = twitter.Api(consumer_key='', consumer_secret='', ...

Crashing due to array usage in C programming: Segmentation fault

When I execute this code, it results in a segmentation fault. However, when I modify the address(LessThan)countarray to address<=countarray, the code runs successfully. I am trying to make it print one less array element, but it seems ...

A circular reference occurs when a base class creates a new instance of a child class within its own definition

My goal is to instantiate a child class within a static method of the base class using the following code: class Baseclass { public static create(){ const newInstance = new Childclass(); return newInstance; } } class Childclass ex ...

Combining two sets of elements in Java to form a Json using Jackson

Is there a way to combine two List of objects retrieved from the database into a single object in order to serialize with Jackson and deserialize in the view? ObjectMapper mapper = new ObjectMapper(); jsonTutorias = mapper.writeValueAsString(tuto ...

Find the closest point within a 2D numpy array

Despite reading numerous posts on finding the closest value in a numpy array or the closest coordinate in a 2D array, none of them address my specific issue. The challenge I'm facing involves having a 2D numpy array structured like this: [[77.6288173 ...

When developing an Angular 2 application using Webpack 2, encountering template parse errors such as 'app' not being a recognized element can occur during deployment

I have encountered an issue with my Angular (v2.4) application using angularfire2. Everything works perfectly in the development environment with the Express server. However, when I build the app using "npm run build", Webpack2 creates a 'target' ...

Enhancing Vue Filtered Lists for Increased Dynamism

Currently, I am iterating through a list of items using the v-for directive. Before displaying the list, I apply a filter based on a specific value using the .filter() method. To switch between different filtered values, I utilize the v-on:click event. How ...

A collection of asynchronous requests stemming from a sole request

I am facing a unique ajax scenario that is proving to be quite challenging for me. Here is the specific sequence of events that I need to coordinate: An initial request returns an array of ID numbers. A separate request needs to be sent for each ID in ...

Exploring a collection of objects in an Angular 2 component

Can someone please assist me in identifying what I am doing wrong or what is missing? I keep getting an undefined value for `this.ack.length`. this._activeChannelService.requestChannelChange(this.selectedchannel.channelName) .subscribe( ...

Personalized data type for the Request interface in express.js

I'm attempting to modify the type of query in Express.js Request namespace. I have already tried using a custom attribute, but it seems that this approach does not work if the attribute is already declared in @types (it only works for new attributes a ...

Why is the wrong value being echoed in this code snippet?

Why is the code echoing an incorrect value? When data is entered into the input field like this it will output 111 8 333 444 8 666 777 8 999 Why is it not echoing 111 222 333 444 555 666 777 888 999 What can be done to resolve this issue? .......... ...

Unexpected error: JSON data at line 1 column 1 of the JSON data is incomplete

I've encountered an issue with my script related to a JSON response error. Below is the code snippet in question: $(document).ready(function() { $('#btndouble').click(function(){ var address = $('#btcaddress').val(); ...