Reformatting function transforms the structure of an array containing objects

I have been struggling with certain issues and would like to find the most effective solution. Despite using map and reduce, I have not been able to achieve the desired results. Any help would be greatly appreciated.

Consider the following INPUT Array structure:

[
{ 'id': 1, 'question_name': "What is your name?", 'question_value': "Jack"},
{ 'id': 2, 'question_name': "What is your hobby?", 'question_value': "Rugby"},
{ 'id': 3, 'question_name': "What is your name?", 'question_value': "Peter"},
{ 'id': 4, 'question_name': "What is your hobby?", 'question_value': "Tennis"}
]

Your task is to create a function that transforms the Array into the desired OUTPUT object:

{
"What is your name?": [{"id": 1, "value": "Jack" }, {"id": 3, "value": "Peter" }],
"What is your hobby?": [{"id": 2, "value": "Rugby"}, {"id": 4, "value": "Tennis"}]
}

Here is a sample code snippet that already exists:

const formatter = (o) => {
 const newObject = Object.keys(o).reduce(elm =>
  ({
    "What is your name?": [{'id': elm, 'value': elm}],
    "What is your hobby" : [{'id': elm, 'value': elm}],
  })
 )
 return newObject

Answer №1

If you're looking to streamline your code, consider utilizing the reduce method.

const data = [
  { id: 1, question_name: "What is your name?", question_value: "Jack" },
  { id: 2, question_name: "What is your hobby?", question_value: "Rugby" },
  { id: 3, question_name: "What is your name?", question_value: "Peter" },
  { id: 4, question_name: "What is your hobby?", question_value: "Tennis" },
]

const res = data.reduce((acc, { id, question_name, question_value: value }) => {
  if (acc[question_name]) {
    acc[question_name].push({ id, value })
  } else {
    acc[question_name] = [{ id, value }]
  }
  return acc
}, {})

console.log(res)


Reference

Check out Destructuring assignment for more information

Explore Array.prototype.reduce for further insights

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

Experiencing problems with the calling convention in JavaScript

Here is a snapshot of the code provided: If the function testFields at Line:3 returns false, then the program correctly moves to Line:21 and returns the value as false. However, if testFields returns true, the program proceeds to Line:4, but instead of ex ...

Navigate to the initial visible element on the specified webpage via the page hash link

In my handlebars HTML template, I have a partial view that includes different pieces of content for desktop and mobile. I use different CSS classes to hide and show these elements accordingly. <div class='hideOnMobile showOnDesktop'> < ...

Converting HashMap to JSON representation

Take a look at this HashMap that I'm attempting to parse: HashMap map = new HashMap(); map.put("bowser", "b=mozilla"); map.put("car", "car=Ford"); map.put("model","model=Mustang"); map.put("Year", 2014); map.put("dealer", "Dealer=AKHI"); I initi ...

How to automatically set the radio button as "checked" with Javascript upon loading the page

With the dark mode switch javascript from Bootstrap 5 (https://getbootstrap.com/docs/5.3/customize/color-modes/#javascript), I am attempting to ensure that a radio button is set to "checked" when the page loads, as well as when the color mode is changed. ...

Integrating custom non-NPM JavaScript files into Angular 2

Currently, the application I am working on is running in an environment with angular 2.0.0 final using typescript and also utilizes angular-cli 1.0.0-beta.15. Since the development of the application involves multiple developers who all use typescript, I ...

In JavaScript, the function is unable to access elements within an iteration of ng-repeat

I am using ng-repeat to display datepickers that are powered by flatpickr. To make this work, a script needs to be added on the page for each input element like so: <script> $('[name="DOB"]').flatpickr({ enableTime: false, dateForm ...

Flask application experiencing JavaScript issues on local host, yet functioning properly when accessed via 127.0.0.1

My web application is built using Python with Flask for the server, and HTML with JavaScript for the user interface that utilizes callback functions and POST methods. While the application runs smoothly with redirections and REST API calls at: Upon click ...

Attempting to send JSON data using a button in a PHP script

I'm facing an issue with trying to add new data to my JSON file using jQuery by inputting values, but nothing seems to happen. I apologize for what may seem like a simple question and appreciate any assistance. As someone who is new to programming, I ...

Angular2 forms: creating validators for fields that are interconnected

Imagine a scenario where a form allows users to input either a city name or its latitude and longitude. The requirement is that the form must validate if the city name field is filled OR if both the latitude and longitude fields are filled, with the added ...

How to sort data in AngularJS by clicking on a column to change the order from ascending to

The code view below is what I am currently working with: <tr ng-repeat="c in clients | orderBy:'code'"> <td>{{c.firstname}} {{c.lastname}}</td> <td>{{c.telephone}}</td> <td>{{c.location}}</td> ...

Adjust the database table when a session expires in PHP

Within my PHP code, there is a session timeout feature that triggers after 60 minutes of inactivity. This code snippet resides in the file /mno.php, where both the login and logout functionalities are also implemented. /mno.php if (isset($_SESSION[' ...

Reorganizing DIV elements on-the-fly

I've recently delved into the world of html, css, and javascript with the hopes of creating my very own news website. However, I've come across a puzzling problem: My vision is to have 10 div blocks on the homepage, each containing a headline wi ...

Enhancing asynchronous loading with Axios interceptors

When utilizing vue.js along with the axios library to make requests to my API, I aim to configure it globally and display a loading message when the request takes too long. I discovered that by using axios interceptors, I can set up axios configuration on ...

Steps to display images within a div from a specific directory

Recently, I have encountered a challenge that involves retrieving images from a specific directory, regardless of the number of images present, and then displaying them in a div using an unordered list. I attempted the following code snippet, but unfortuna ...

Using the `scrollIntoView()` method to continuously scroll through elements in Puppeteer

My goal is to extract a list of posts while the page is continuously loading. I am using scrollIntoView() for each element within a loop. Currently, my code looks like this temporarily. When the page loads, the result bounces out without any errors. for (l ...

Unusual scroll bar movements when using jQuery validation

When I click the Add Dependent link button, I wanted the scroll bar to automatically scroll to the bottom, and it does just that. However, there is a small issue after the postback where the text "Please fix the following problems:" briefly appears, even t ...

Deliver a variety of JSON responses

I have created an API that retrieves JSON responses from the Google Places API and stores them in a database. The code sample below demonstrates how it iterates through a list of PlaceIds using a For loop to fetch each one and then proceeds to post them to ...

Unable to properly utilize environment variables on Vercel when using Nuxt framework

I'm encountering difficulties accessing my environment variables on Vercel. When I test the site on my localhost, everything works fine; however, once it's deployed to Vercel, the access to environment variables in my components and plugins direc ...

jQuery Plugin - iDisplayLength Feature

I am currently using DataTables version 1.10.10 and I am looking to customize the main plugin Javascript in order to change the iDisplayLength value to -1. This adjustment will result in displaying "All" by default on all data tables, allowing users to fil ...

Apply CSS styles from a text area using v-html

I am currently working on developing a unique WYSIWYG application where users have the ability to write CSS in a textarea field and view its direct impact on the HTML content displayed on the page. As I was experimenting with different approaches, I attemp ...