What is the best way to transform an Object {} into an Array [] of objects with varying structures?

Within my javascript code, I am working with an object structure like this:

let obj= 
{
  a: {
       a1: [5,5],
       a2: [6,6]
     },
  b: {
       a1: [7,7],
       a2: [8,8]
     },
  c: {
       a1: [9,9],
       a2: [3,3]
     }
}

The goal is to transform it into an array structured as follows:

let arr = 
[
  {
    name: 'a1',
    a: [5,5],
    b: [7,7],
    c: [9,9]
  },
  {
    name: 'a2',
    a: [6,6],
    b: [8,8],
    c: [3,3]
  }
]

My attempt to achieve this with Object.entries(obj).map(([key, value]) => ({key,value})) didn't give me the desired structure. Any insights on how to reconfigure it would be greatly appreciated.

Thank you!

Answer №1

If you want to transform an object using reduce along with Object.entries, you can achieve this by then using Object.values to access the transformed object.

let object = {"a":{"a1":[5,5],"a2":[6,6]},"b":{"a1":[7,7],"a2":[8,8]},"c":{"a1":[9,9],"a2":[3,3]}}

const result = Object.entries(object).reduce((accumulator, [key, value]) => {
  return Object.entries(value).forEach(([subKey, subValue]) => {
    if (!accumulator[subKey]) accumulator[subKey] = {name: subKey,[key]: subValue}
    else accumulator[subKey][key] = subValue
  }), accumulator
}, {})

console.log(Object.values(result))

Answer №2

To accomplish the same task, you can utilize Object.keys in conjunction with Array.reduce:

let data = { x: { x1: [10, 10], x2: [20, 20] }, y: { y1: [30, 30], y2: [40, 40] }, z: { z1: [50, 50], z2: [60, 60] } }

const finalResult = Object.keys(data).reduce((accumulator, key) => (Object.keys(data[key]).forEach(subKey => {
  accumulator[subKey] = accumulator[subKey] || { label: subKey }
  accumulator[subKey][key] = data[key][subKey]
}), accumulator), {})

console.log(Object.values(finalResult))

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

The FormData() object in Django backend is consistently found to be void of any data

I am currently experimenting with uploading an HTML form through AJAX using pure JavaScript, without jQuery. The form is put together in my template by combining three components: the CSRF token, a ModelForm, and a regular Django form (forms.Form). The vis ...

Unable to perform a fetch request in IE9 after the page has finished loading

I'm currently encountering an issue with my Node and Express server setup. I have a separate API on a different server that needs to be accessed, but everything works fine except in IE9. The problem arises when I try to make a call to the API after lo ...

Angular modules are designed to repeat chunks of code in a

Whenever I scroll the page, my function pushes items to an array. However, I am facing an issue where the pushed items are repeating instead of adding new ones. Solution Attempt onScroll(): void { console.log('scrolled'); var i,j,newA ...

Eliminate any unnecessary tags located before the text

I am facing a challenge with the following code snippet. The Variable contains a string that includes HTML tags such as <img>, <a>, or <br>. My goal is to eliminate the <img> tag, <a> tag, or <br> tag if they appear befo ...

Using framer-motion with Next.JS ensures that content remains consistent during navigation

I added a Link on my homepage that connects to the About Us page: <Link href="/about"><a>About us</a></Link> In my _app.js file, there is an AnimatePresence wrapper: <AnimatePresence exitBeforeEnter> <Component {...p ...

Transform your CSS styles into Material-UI makestyles

I am looking to implement an IconButton with a website preview feature that appears when the user hovers over the help icon. I came across a similar solution using CSS, but I need to convert it to Material UI. Here is the CSS code that needs to be converte ...

The issue of variable being undefined in JSON for JavaScript and Python

Consider a scenario where you have the following JSON object (remove the semicolon for python): values = { a: 1, b: { c: 2, d: { e: 3 } }, f: 4, g: 5 }; When attempting to print values in JavaScript, it will work pr ...

Prevent selection based on JSON information

I am utilizing the Jiren filter library to sort through JSON data. If a particular filter criteria does not match any of the results, I would like to disable that option in the select dropdown. For instance, if "Silversea Expedition" is not found in my re ...

What is the process of invoking a function on a specific element when it is encapsulated within an if statement in Meteor.js

Here is an example: {{#if currentUser}} <li><a class="waves-effect waves-light btn modal-trigger modal-close" href="#upload">Upload Image</a></li> {{/if}} Currently, I am implementing the following: Template.MasterLayout.onRe ...

Utilize Bootstrap multiselect for extracting values from optgroups and options

Having a select element with optgroups and bonded values, the structure is as follows: <select id="example-dataprovider-optgroups" multiple="multiple"> <optgroup label="Lime No. 2" value="b3a2eff6-5351-4b0f-986 ...

Detecting changes in a readonly input in Angular 4

Here is a code snippet where I have a readonly input field. I am attempting to change the value of this readonly input from a TypeScript file, however, I am encountering difficulty in detecting any changes from any function. See the example below: <inp ...

Delay the v-alert display after an item is added to the array basket using setTimeout

here is my custom rightTableMenu template <template> <div> <h1 align="center">{{ title }}</h1> <v-alert type="info" icon="mdi-emoticon-sad" v-if="basketStatus"> Empty Basket, please add some to basket < ...

Internal server error frequently occurs when there is an issue with Ajax requests in a Laravel application

Greetings, fellow developers! I am encountering an issue with the comments system in Laravel and Ajax. While it functions correctly with PHP alone, I am facing difficulties when using Ajax. The error message I am receiving is as follows: Status Code:50 ...

Creating a Build System for JavaScript in Sublime Text

While working on developing an application using node.js, I decided to create a JavaScript build system in Sublime Text 3 on my Ubuntu OS. I made a new build system file named nodey.sublime-build with the following contents: { "cmd": ["node","$file"," ...

Why isn't $.post functioning properly in any instance?

I've been experiencing issues with my $.post calls throughout my code. Despite not sending requests to different domains, everything is localhosted. My Mac OS X 10.8 automatically defined my localhost alias as ramon.local, and I'm trying to make ...

Top method for centering a flexible SVG vertically once the page width becomes too narrow

Currently, I have two SVG images displayed side by side on a webpage. One SVG needs to maintain a fixed size while the other should scale as needed, and I have achieved this functionality. However, I am facing an issue where I want the two SVGs to align v ...

"Viewed By" aspect of Facebook communities

I'm working on implementing a feature that shows when a post has been seen, similar to Facebook groups, using JS and PHP. I've been able to track the number of times a post has been seen through scrolling actions, but now I want to determine if u ...

What is the best way to apply a class for styling my JavaScript code in CSS? I'm having trouble getting classList

I am having trouble adding a class to my JavaScript script in order to animate the images created in JavaScript to fall off the page. I have tried using the code element.classList.add("mystyle");, but every time I insert it, my JavaScript stops working. T ...

Having difficulty pushing a float array in the C++ standard library stack implementation

I am struggling with pushing an array to the stack. I anticipated this process to be simple, but it has become quite time-consuming trying to resolve this issue. My expectation was to push arrays just like I do with integers or floats, however, that is no ...

Hide Material UI Drawer when clicking elsewhere

Attempting to implement the Drawer component in Material UI React. Want to ensure that the state within the Drawer component persists even when the Drawer is closed, so passing variant="persistent" in Drawer component. The issue arises with the ...