Rearrange the shape of an array of objects into a new array structure

Is there a way to restructure this data?

const arr = [
  {
    "name": "a_1",
    "v": 1
  },
  {
    "name": "b_1",
    "v": 1
  },
  {
    "name": "a_2",
    "v": 2
  },
  {
    "name": "b_2",
    "v": 3
  }
]

into this format?


[{
  a: 1,
  b: 1
}, {
  a: 2,
  b: 3
}]

I have attempted using forEach and split('_').pop() to extract the group key from the name, but am struggling with grouping them together.

Answer №1

One method that could be used is to utilize the reduce() function on the input array in order to create a temporary map object that establishes a relationship between the number following the underscore (key) and the "v" number (value). The desired outcome can then be achieved by retrieving an array of values from the map object using Object.values():

const arr = [{
    "name": "a_1",
    "v": 1
  },
  {
    "name": "b_1",
    "v": 1
  },
  {
    "name": "a_2",
    "v": 2
  },
  {
    "name": "b_2",
    "v": 3
  }
];

const result = Object.values(arr.reduce((map, item, index) => {

  // Extract data from current item of arr
  const { name, v } = item;
  
  // Split name into letter and key parts
  const [letter, key] = name.split("_");

  // Retrieve existing obj for key from mapping
  // or initialize empty object for new key
  const obj = map[key] || {}

  // Update letter with v for current obj
  obj[letter] = v;

  // Update mapping with updated key/obj
  return {...map, [key] : obj };

}, {}));

console.log(result);

Answer №2

If you maintain the order of your array, you might want to consider this recursive approach

const arr = [
  {
    name: "a_1",
    v: 1
  },
  {
    name: "b_1",
    v: 1
  },
  {
    name: "a_2",
    v: 2
  },
  {
    name: "b_2",
    v: 3
  }
];


const finalArr = []
function reduce(arr){
    if(arr.length === 0){
        return;
    }
    const [one, two] = arr;
    finalArr.push({[one.name.split("_")[0]]: one.v, [two.name.split("_")[0]]: two.v});
    reduce(arr.slice(2))
}
reduce(arr);
console.log(finalArr);

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

What are some effective strategies for reducing excessive re-rendering of React components?

Here is how I am displaying a list of components on the screen: const MessagesContainer = ({ messages, categories, addHandler }) => { const options = categories.map(category => ( { value: category.name, label: category.name } )); ...

The button functionality gets hindered within the Bootstrap well

I'm trying to figure out what's wrong with my code. Here is the code: https://jsfiddle.net/8rhscamn/ <div class="well"> <div class="row text-center"> <div class="col-sm-1">& ...

Converting units to rem dynamically in CSS: a comprehensive guide

Hey there, I'm currently trying to dynamically convert units into rem in CSS and facing some issues. I have set the root font-size as 23px The current font-size is 16px The expected result should be 16 / 23 => 0.695rem Question: I am looking for ...

Shifting Icon to the Right within the Drawer Navigator Toolbar

While modifying the example code for Material UI's drawer navigator, I decided to enhance it by adding a notification icon and a checkout icon with the Admin Panel typography in the toolbar. However, I encountered an issue where the checkout icon app ...

Is it possible to convert a string of elements in JavaScript into JSON format?

Within my JavaScript code, a variable holds the following information: url=http://localhost quality=100 tag="4.4, 5.5" I am interested in converting this data to JSON format using JavaScript, like this: "result": { "url": "http://localhost", "qu ...

Re-establishing Scroll Functionality Post Ajax Request Disruption caused by prettyLoader

I have created a jQuery infinite scroll function that follows the infinite scroll design pattern. After the ajax server call is completed, I am trying to rebind the scroll event. Although everything works fine for the first ajax call, the scroll event is ...

Following the antd migration from version 2.0 to 3.0, there was a noticeable default font size increase from 12px to 14px. Are there any methods available to personalize the antd font size?

Looking for assistance in adjusting the font-size of an antd table from 14px to 12px following a migration from antd 2.0 to 3.0. Any suggestions or help would be greatly appreciated! ...

Display the source code of an HTML element when clicked

Is there a way to show the source code of an element on a webpage in a text box when that specific element is clicked? I am wondering if it is feasible to retrieve the source code of an element upon clicking (utilizing the onClick property), and subseque ...

Ways to display and conceal login and logout buttons in the AppBar based on the login status of another component through the utilization of local storage

Within my App component, there is a rendering of the MyAppBar component featuring Login and Logout buttons. Additionally, the App component renders a Login form component which contains a button responsible for adding user information to local storage, sim ...

The Chrome browser's memory heap is reported to be a mere 10 MB, yet the task manager displays a whopping

When using Chrome's memory profiler, I notice that the heap size is always around 10 MB. However, the memory in my task manager keeps increasing and can reach over 1 GB if I leave my website running. Even though the heap size remains less than 10 MB w ...

"Encountering a bug when attempting to load Google Maps while hiding it

I encountered a bug while setting up a google map on a hidden tab. The map is scrollable and zoomable, but it doesn't extend across the entire canvas - leaving the rest of the canvas in grey. Using the jQuery Map Extension (http://code.google.com/p/j ...

Trouble with bootstrap 5 nested accordions: panels won't collapse as expected

I've structured my page content using nested bootstrap accordions within Bootstrap 5. The primary accordion is organized by continents, with each panel containing a secondary accordion for individual countries. While the main accordion functions cor ...

Should I use React with Spring Boot or just Spring Boot for this project?

My partner and I are collaborating on a project for our current semester course. As we delve into our research on potential technologies to use, it seems like Spring Boot for the server side along with MySQL or Postgres for the database are emerging as s ...

Unraveling cryptic error messages in Google Closure-compiled JavaScript stack traces

We've developed a reporting system that automatically captures and organizes error stack traces from a dynamic web application built with Google Closure. Currently, I possess the source maps stored on the server and am seeking a straightforward metho ...

How to configure Jest and React Testing Library with NextJS in TypeScript – troubleshooting issue with setting up jest.config.js

I am currently setting up Jest with a NextJS application, and in my jest.config.js file I have configured it as follows: module.exports = { testPathIgnorePatterns: ["<rootDir>/.next/", "node_modules/"], setupFilesAfterEnv: ...

How can multiple elements be connected to an onclick action?

I'm having trouble figuring out how to use an onClick action with jQuery for all the elements in a list of attached files. Here is a snippet of my HTML file: <p>Attachments</p> <div> <ul id="attach"> <li id="KjG34 ...

Converting an Object into an Array of Objects

The question at hand is quite simple yet lacks a definitive answer. I have an object and my objective is to take each key and value pair, transform them into objects, and then push them into an array. To illustrate this, consider the example below. { tit ...

Using jQuery to submit a form via ajax and retrieve values from a datepicker and button

Currently, I am in the process of configuring my ajax form to display an alert box when it either succeeds or fails. The form includes options for two different boxes, a datepicker, email address input, and phone number input. My main query is regarding ho ...

Custom mute bot using Discord.js with the ability to specify duration and provide a reason

I'm creating a discord.js mute bot and encountering some issues with its functionality. Is there a way to program it so that when someone types the command !mute User, it automatically sets the time to 30min and the reason as No reason Specified. How ...

Tips for automatically scrolling to the bottom of a div when new data is added

I'm working on a project with a table nested inside a div, and it has some unique styling: #data { overflow-x:hidden; overflow-y:visible; height:500px; } Currently, as the table fills up with data, a vertical scroll bar appears. But I wa ...