Transform the array of objects into different clusters

I am facing a challenge where I have an object returning two arrays of objects from an API. My goal is to transform this data into a new array of objects in order to effectively group the information for the Vue v-select component. For a visual representation, you can check out this CodePen Example.

fields: {
      current: [
        {
          name: 'Date'
        },
        {
          name: 'Time'
        }
      ],
      previous: [
        {
          name: 'Birthday'
        },
        {
          name: 'Comments'
        }
      ]
    },

I am looking for a solution on how to convert the existing data structure into a new array that follows this format:

grouped: [
      {
        group: "Current",
      },
      {
        name: "Date"
      },
      {
        name: "Time"
      },
      {
        group: "Previous"
      },
      {
        name: "Birthday"
      },
      {
        name: "Comments"
      },
    ]

Answer №1

Utilize the Object.entries() method to retrieve the different groups along with their values, then leverage Array.flatMap() to map them accordingly. Generate an object for each group and append it to an array containing all items within that group.

const extractGroups = data =>
  Object.entries(data)
    .flatMap(([group, elements]) => [{ group }, ...elements])

const data = {"current":[{"name":"Date"},{"name":"Time"}],"previous":[{"name":"Birthday"},{"name":"Comments"}]}

const output = extractGroups(data)

console.log(output)

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

Issue with setting and showing the PHP data array within the vue.js variable

I am encountering an issue with transferring an array of data from a PHP session variable to a Vue.js variable Here is how I am trying to assign an array of data to a Vue.js variable: permissions:['<?php echo json_encode($_SESSION['permission ...

Transferring data from one array to another in MIPS32 assembly

Looking for guidance on converting a section of C++ code to MIPS using direct translation. Everything is almost complete, except for a line inside a do-while loop that involves x[i] = y[i]. Struggling to understand the MIPS conversion of this particular li ...

Analyzing the efficiency of the Scala Arrays tail function

According to Scala documentation, the performance of accessing the tail for an Array sequence is stated as Linear, while accessing the head is described as having a performance of Constant. Despite the entire block containing array elements being brought ...

The aspect ratio of an image is being calculated by loading the image twice

I am currently facing the issue where the same image is loading twice for a single preview. The first time the image is loaded for preview purposes in an iframe. The second time, the image metadata such as width and height are fetched with the same path. ...

Issue: Package 'cairo' not located on EC2 Bitnami MEAN server

Setting up my MEAN application on a Bitnami server has been quite a challenge. During the installation of dependencies, I encountered an error that I just can't seem to resolve. Despite following the instructions provided in the error message, I am st ...

Leveraging the flexibility of an undefined variable as a useEffect dependency

Summary: Need help using listRef.current.clientWidth as a dependency in useEffect. I'm working on creating a dynamic list that automatically adjusts the width of its items based on the list's width. I've almost got it working, but I'm ...

Step by step guide on integrating ReactJS into your current node.js backend application

I am currently working on a basic node.js API Setup: | project-name | public | index.html | ... some static js/css | app.js | package.json app.js var express = require('express'), bodyParser = require('body-parser'), ...

Displaying information in ejs format

I am currently working on a project to develop a basic webpage that requires the user to input a specific time and then click on submit. Once submitted, I want the relevant data linked to that input to be displayed on the webpage. Upon clicking the submit ...

Renew the Look of Dynamic HTML with Updated Styles

In the middle of my website, there is a console that contains links to dynamically update its content using javascript. Everything works smoothly, but the new HTML added dynamically does not have any styling applied to it. Is there a way to refresh the CS ...

Struggling to dynamically append additional textboxes to a <div> element using JavaScript

After spending over 12 hours on this problem, I am completely stuck and frustrated. I have tried countless variations and sought out other solutions to no avail. It should be a simple task. My project involves using JQueryMobile 1.2 along with its dependen ...

fnRedraw and fnReloadAjax do not have the capability to refresh the datatable

I have been working on updating a table with new data from an ajax url. The table loads correctly the first time, but I am struggling to get it to refresh. $(function() { var datepicker = $( "#date-picker" ); var table = $("#reports1").dataTable( ...

Issue with FileStreamResult not triggering download prompt after AJAX call in MVC

I am encountering an issue with my code that is triggered by the "export" li tag. It converts a FusionChart to an SVG string and then sends it to my controller via an ajax call. The problem I'm facing is that even though the controller receives the r ...

Tips for Incorporating xmlhttp.responseText in If Statements

This is the code snippet from my save_custLog_data.php file: <?php $a = $_GET['custEmail']; $b = $_GET['pswrd']; $file = '/home/students/accounts/s2090031/hit3324/www/data/customer.xml'; if(file_exists($fi ...

What is the best way to target and manipulate the transform property of multiple div elements in JavaScript?

Looking at this code snippet, my goal is to have all the boxes rotate 180deg with a single click, without needing to apply different ID names: function rotateAllBoxes() { var boxes = document.getElementsByClassName("box"); for (var i = 0; i < box ...

Conceal a div once the content in a separate div has finished loading

After loading an image in slices inside a div, I want to ensure that the entire content is loaded before displaying the div. To achieve this, I am using another div as a mask while the content loads: <div id="prepage" style="position:absolute; left:0px ...

Choose a random subset from a collection of dictionaries based on certain criteria

I am dealing with a collection of dictionaries structured as follows: list_of_dicts = [ {'db': 'redshift', 'table': 'metrics', 'prefix': 'abc_'}, {'db': 'blueshift', &a ...

Images cannot be uploaded using ajax

I have been troubleshooting an issue with uploading image files using ajax without refreshing the page. However, I am facing a problem where the file does not get moved to the specified folder even after implementing basic PHP code for file upload. if($_S ...

JavaScript Scroller that keeps on scrolling

Unique Continuous JavaScript Scroller I am currently working on a JavaScript scroller script that enables left to right and right to left scrolling on the click of next and previous buttons. The script is designed to work with 1 to 3 div elements in a con ...

Technique for seamlessly moving between subpages and main page while scrolling to a specific id

I'm struggling with coding and thought I'd reach out for help here. Can anyone provide a solution to my problem? Issue - I have a navigation link on my main page that scrolls to an ID using jQuery. It works fine on the main page, but not on any ...

Unable to resolve the issue of Duplicate keys detected with value '0'. This could potentially lead to errors during updates

Encountered a warning in Vue js stating 'Duplicate keys detected: '0'. This warning could potentially lead to an update error. To resolve this issue, I utilized the getter and setter in the computed variable and dispatched the value to Vuex ...