Tips for extracting individual keys from an object and transferring them into a separate object

I have an array of objects containing all the form data. However, I need to format this data differently before sending it to the backend. Each object needs to be fetched separately and then pushed into another object as shown below. The current data looks like this:

[
    {
        "messageType": "test",
        "eligibleUsers": "test2",
        "rules": [
            {
                "ruleId": "qwer",
                "value": "qwert"
            },
            {
                "ruleId": "testing",
                "value": "testing"
            },
            {
                "ruleId": "newtest",
                "value": "newtesting"
            }
        ]
    },
    {
        "messageType": "add",
        "eligibleUsers": "newadd",
        "rules": [
            {
                "ruleId": "qaz",
                "value": "qaz"
            }
        ]
    },
    {
        "messageType": "neww",
        "eligibleUsers": "add",
        "rules": [
            {
                "ruleId": "data",
                "value": "data1"
            },
            {
                "ruleId": "data2",
                "value": "dat3"
            }
        ]
    }
]

However, I would like the data to be structured like this:

{
        "questions": [
            {
                "id": null,
                "ques": "test",
                "type": "dropdown",
                "message_user_type": "self",
                "rules": [
                    {
                        "rule": "qwer"
                    },
                    {
                        "rule": "testing"
                    },
                    {
                        "rule": "newtest"
                    }
                ]
            },
            {
                "id": null,
                "ques": "test2",
                "type": "dropdown",
                "message_user_type": "emp",
                "rules": [
                    {
                        "rule": "qwert"
                    },
                    {
                        "rule": "testing"
                    },
                    {
                        "rule": "newtesting"
                    }
                ]
            },
            {
                "ques": "add",
                "rules": [
                    {
                        "rule": "qaz"
                    }
                ]
            },
            {
                "ques": "newadd",
                "rules": [
                    {
                        "rule": "qaz"
                    }
                ]
            },
            {
                "ques": "neww",
                "rules": [
                    {
                        "rule": "data"
                    },
                    {
                        "rule": "data2"
                    }
                ]
            },
            {
                "ques": "add",
                "rules": [
                    {
                        "rule": "data"
                    },
                    {
                        "rule": "data2"
                    }
                ]
            }
        ]
    }

I would appreciate any assistance with this! Thank you in advance.

Answer №1

To kickstart this task, begin by utilizing Array.map in this manner:

const data = [
  {
      "messageType": "test",
        "eligibleUsers": "test2",
        "rules": [
          {
              "ruleId": "qwer",
                "value": "qwert"
            },
            {
              "ruleId": "testing",
                "value": "testing"
            },
            {
              "ruleId": "newtest",
                "value": "newtesting"
            }
        ]
    },
    {
      "messageType": "add",
        "eligibleUsers": "newadd",
        "rules": [
            {
                "ruleId": "qaz",
                "value": "qaz"
            }
        ]
    },
    {
        "messageType": "neww",
        "eligibleUsers": "add",
        "rules": [
            {
                "ruleId": "data",
                "value": "data1"
            },
            {
                "ruleId": "data2",
                "value": "dat3"
            }
        ]
    }
]
  
const questions = data.map(obj => {
  return {
    "id": null,
    "ques": null,
    "type": null,
    "message_user_type": null,
    "rules": obj.rules.map(rule => ({ rule: rule.ruleId }))
  }
})

const result = { questions }

console.log(result)

By using Array.map, the resulting array will maintain the same length as the original array. For more complex operations, consider utilizing Array.reduce.

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

Webpack 2.7.0 throws an error: "Unexpected parameter: theme"

At the moment, I am on webpack 1.16.0 and using --theme as an argument to set the output path and plugin paths. The command appears as: rimraf dist && webpack --bail --progress --profile --theme=<name of theme> However, as I try to upgrade ...

What is the best way to combine async/await with a custom Promise class implementation?

I've created a unique Promise class. How can I incorporate it with async/await? type Resolve<T> = (x: T | PromiseLike<T>) => void type Reject = (reason?: any) => void class CustomizedPromise<T> extends Promise<T> { ...

Is there a solution available for the error message that reads: "TypeError: Cannot set value to a read-only property 'map' of object '#<QueryCursor>'"?

Everything was running smoothly in my local environment, but once I deployed it on a Digital Ocean Kubernetes server, an error popped up. Any assistance would be greatly appreciated. https://i.stack.imgur.com/VxIXr.png ...

The setInterval function continues executing even after the page has been changed

I'm encountering an issue with my function where it continues to run even after the page has changed, resulting in an error. How can I go about stopping this behavior? Thank you! componentDidMount() { var current = 0; var slides = document.g ...

Is there a way to deactivate the spin buttons for an input number field?

Is there a way to create an input element with type number in Vue using createElement() in TypeScript and then disable the spin buttons for increment and decrement? I attempted to use the following CSS: input[type=number]::-webkit-inner-spin-button, input ...

Using angular2's ngRepeat to iterate over XML data

I have successfully transformed my XML data into JSON format to be utilized in Angular 2 within my view. However, as I attempt to loop through the data using a for(var... loop, I encounter an error message stating that it cannot find name array and that th ...

Issue detected in rxjs-compat operator's shareReplay file at line 2, column 10:

I've encountered an issue with the angular material spinner I'm using in my project. The error message is as follows: ERROR in node_modules/rxjs-compat/operator/shareReplay.d.ts(2,10): error TS2305: Module '"D:/ControlCenter/ofservices ...

Display content from an external HTML page within a div using Ionic

Currently, I am facing an issue where I am utilizing [innerHtml] to populate content from an external HTML page within my Ionic app. However, instead of loading the desired HTML page, only the URL is being displayed on the screen. I do not wish to resort t ...

Tips for fixing the error message "unable to access property 'property-name' of null"

I need assistance with retrieving data from a firebase database and storing it in an array using typescript. Below is the code snippet I am working with: export class ViewUserPage { public list = []; public ref = firebase.database().ref(); public ...

Concealing tab bars on Ionic 2 secondary pages

In my Ionic Bootstrap configuration, I have the following setup: { mode: 'md', tabsHideOnSubPages: true } However, despite having this setting in place, the tabs still appear on some sub-pages. It seems to be happening randomly. Is there ...

Encountering ng build --prod errors following Angular2 to Angular4 upgrade

Upon completing the upgrade of my Angular2 project to Angular4 by executing the following command: npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @an ...

Variations in default export behavior in Webpack when using Typescript versus Javascript

In my React application, I have a page that imports a component from another file. // Code snippet from IconPage.tsx import {AccountBalanceIcon} from './icons'; <AccountBalanceIcon /> // Code snippet from ./icons.ts export { default as A ...

Steps for generating a signal that postpones the primary signal and promptly resets

I am looking to create a signal that will automatically switch to an underlying signal or memo after a specific delay, and reset immediately if the primary signal is cleared. The code snippet below illustrates my desired functionality. import { render } fr ...

What is the best way to ensure that multiple queries are returned in the correct sequence?

In the interface below, there is a search input box along with data displayed. As you type in the search input, the data below filters accordingly. Each letter typed triggers a request to retrieve the relevant data. For instance, if you type "folder," the ...

Utilizing various filters and sorting options on API response within Angular 8

Upon receiving the following API response: [ { "imgPaths":[ "gallery/products/55ccb60cddb4d9bded02accb26827ce4" ], "_id":"5f3e961d65c6d591ba04f3d3", "productName":" ...

Utilizing TypeScript 2's Absolute Module Paths

The issue at hand: I am facing a challenge with relative module paths and have attempted to resolve it by configuring the baseUrl setting in my tsconfig.json file. Despite my efforts, I keep receiving an error indicating that the module cannot be found. I ...

Is there a way to receive a comprehensive report in case the deletion process encounters an error?

Currently, I am performing a delete operation with a filter based on 2 fields: const query = await Flow.deleteOne({ _id: flowId, permissions: currentUser!.id, }); After executing the delete operation, I inspect the query object to determine its su ...

The Bootstrap carousel is experiencing compatibility issues with Angular 7 and is currently not functioning properly

I'm currently using the bootstrap multi carousel, and it works perfectly without a loop. However, when I try to implement it dynamically using an ngFor loop, it doesn't function as expected. Instead of sliding with multiple images, it just displa ...

ngClass is failing to be implemented

Does anyone know how to dynamically apply a CSS style to an input based on a variable value? HTML <input class="defaultInput" [ngClass]="{'inputerror':'emptyFields'}" formControlName="idAnnuaire" placeholder="Ex: c20011"> CSS ...

Show a select element with choices that change depending on another select element

I am currently working on a select dropdown component that utilizes the @Input option variable. My goal is to have another instance of this component display options based on the selection made in the first instance. Any suggestions on how to make this h ...