Is it feasible to extract the Json object from its current location within another object?

Is there a way to manipulate this JSON data?

"forms": [
    {
        "_id": "Untitled Form",
        "title": "Untitled Form",
        "answer": [
            {
                "username": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f555e514c5a514c4b5e510d0b0e0f7f58525e5653115c5052">[email protected]</a>",
                "date": "2022-11-02",
                "formId": "6361c5aaf7a02c177ebebb27",
                "answers": {
                    "test": [
                        "New Option"
                    ],
                    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcd6d3d4d2fcd2dddeddc8d5cfd2dddfd792dfd3d1">[email protected]</a>",
                    "dropdown": "New Option",
                    "radio": "3",
                    "date": "2022-11-01T00:00:00.000Z",
                    "time": "17:25"
                }
            },
            {
                "username": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95f4f1f4f8d5e2f0f2faf1f0e3bbf6faf8e6">[email protected]</a>",
                "date": "2022-11-03",
                "formId": "6361c5aaf7a02c177ebebb27",
                "answers": {
                    "test": [
                        "New Option"
                    ],
                    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b18083828083829f8083828083f1d49fd2dedc">[email protected]</a>",
                    "dropdown": "3",
                    "radio": "3",
                    "date": "2022-11-16T00:00:00.000Z",
                    "time": "09:44"
                }
            }
        ]
    }
]

I attempted to iterate through it using JavaScript but the returned value is not as expected, and only seems to increment the array values. I tried implementing some logic but couldn't achieve the desired output.

const newData = forms.map((item) => {
        var mappedAns = item.answer.map((data) => {
          let data_fix = {};
          Object.keys(data.answers).forEach((key) => {
            data_fix[
              key
                .replace(/[{()}]/g, "")
                .replace(/ :/g, "")
                .replace(/ /g, "_")
                .toLowerCase()
            ] = data.answers[key];
          });
          return { ...data, data_fix };
        });
        return { ...item, answer: mappedAns };
      });

Answer №1

const updatedData = forms.map((element) => {
  var transformedAnswers = element.answer.map((info) => {
    Object.keys(info.responses).forEach((k) => {
      info[
        k
          .replace(/[{()}]/g, "")
          .replace(/ :/g, "")
          .replace(/ /g, "_")
          .toLowerCase()
      ] = info.responses[k];
    });
    delete info.responses;
    return { ...info };
  });
  return { ...element, answer: transformedAnswers };
});

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

I am attempting to verify a user's login status with Next.js and Supabase, however, I am encountering difficulties in making it function properly

I recently cloned this repository from https://github.com/vercel/next.js/tree/canary/examples/with-supabase-auth-realtime-db and I'm trying to implement a navigation bar that changes based on the user's login status. Unfortunately, the code I&ap ...

Combining JSON objects in a Pentaho JavaScript JSON by matching keys to merge with an existing JSON document

My goal is to construct a Json document by breaking it down into smaller pieces, with each piece containing the necessary keys to insert the smaller Json bits into the correct json structure. As I am relatively new to JavaScript and still in the process of ...

Search the database using a single text field and then automatically fill in the remaining fields using PHP

Being a beginner in PHP and Ajax, I find myself quite lost in the process. I have set up a MySQL database and created several forms in PHP. One of the forms is supposed to display customer information with text fields, including a search field for phone nu ...

Implementing dynamic webpage updates based on dropdown list selections

In my webpage, I am displaying a list of movies fetched from an API. The issue I am facing is related to sorting the movies based on user selection. When I uncomment one of the sort methods in my code, it works as intended. What I want to achieve is that ...

Redefining the onClick function in the Redux 'presentation' component to include parameters

How can I pass an object as an argument to a function in a redux "presentation component" efficiently? In my <BookList /> container component, I display a <BookListRow/> presentation component for each book. I want to add a button in each Boo ...

Javascript error in formatting

Currently, I am utilizing an inner join operation on three tables and displaying the resulting table using XML. <SQLInformation> <Table>tblechecklistprogramworkpackagexref prwpxref</Table> <TableJoins> INNER JOI ...

Are there alternative methods for retrieving data in Vue Hacker News besides using prefetching?

I am currently developing a Vue single page application with server side rendering using Vue SSR. As per the official documentation, data in components will be prefetched server-side and stored in a Vuex store. This process seems quite intricate. Hence, ...

Wind: incorporateComplexType into addEntityType with entityTypes collection

My .NET entity looks like this: public class Customer { public long Id { get; set; } public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public DateTime BornOn { get; set; } ...

Extracting Ajax responses and storing them as variables in JavaScript

Currently, I am developing a small PHP script and using the following code for an ajax query: var CODE = $('.code').val(); var CASE = $('.code').attr('case'); $.ajax({ type:'POST', ...

Utilizing Prototype in Node.js Modules

Currently, I am working on a project involving multiple vendor-specific files in node. These files all follow a similar controller pattern, so it would be more efficient for me to extract them and consolidate them into a single common file. If you're ...

the jquery auto complete plugin is having trouble parsing the data as JSON

I am trying to integrate an auto-complete feature into a Rails application and have opted for the jQuery auto-complete plugin. The goal is to implement this feature for a specific array, as shown below. @testers = User.find_by_sql("select * from users w ...

Innovative ways to design a responsive carousel with Bootstrap

My goal was to create a slider with divisions inside a bootsrap carousel, and here is what I did. However, I am looking for guidance on how to adjust it so that on screens smaller than sm (of bootstrap), there are only two divisions in one carousel, and a ...

When I attempt to open a file with a double click in my Electron app, Argv[1] gives me an unexpected value

When attempting to open a file by double-clicking, I encounter an issue while using electron-packager to build the application for the Mac App Store. Although I have set up the electron app to launch when a file is double-clicked, it appears that the file ...

Guide to retrieving objects in React.js

Struggling to extract a country from an online JSON file that I am currently fetching. I am attempting to streamline the process by creating a function to retrieve the country from the dataset and avoid repeating code. However, I am encountering difficulti ...

Receiving null value with Web API POST using [FromBody]

Below is the code for my WebAPI in C#: [Route("")] [HttpPost] public void SaveTestRun([FromBody] object data) { inputResultsToDatabase(data); } This is the ajax request I am making: sendTestData() { t ...

Customizing JSON response with Spring MVC

I'm facing a challenge with my RestController method that returns data in a custom JSON format. Originally, I was using a HashMap to build the response: // The method which builds custom JSON response from retrieved data public List<HashMap<Str ...

when the window is scrolled a certain amount, use jQuery to scroll back in the opposite direction

Using jQuery for Background Image Position: $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll >= 50) { $(".class").addClass("bgposi"); // $(".top").addClass("fixd"); // $(".logo").addClass ...

Troubleshooting Node.js Application: Investigating Port Errors

After cloning a node.js application, I went through the setup process by running npm install and npm install -g nodemon. In order to run the application locally on port 3000, I added the following line in my app.js file: app.listen(3000, () => console. ...

Guide on transforming Json information into the preferred layout and iterating through the loop

Currently, I am diving deep into the world of JSON and feeling a bit puzzled by data formats, arrays, objects, and strings. First things first, I'm in need of data structured like this (on a jQuery page). Would this be considered an object or an arra ...

Downloading PDFs using the REST API in EXTJS 4.2

As a newcomer to EXTJS4.2 and web development, I have been trying to understand a particular issue that has left me confused. In my AJAX code, I am calling a REST API using POST with JSON input parameters in order to download a PDF file. Some sources cla ...