Building a hierarchical object structure from an array

I am working with an array of objects that looks like this:

const sorted = [
{
IsoCode: "EUR",
Buy: 1.948,
Sell: 1.963
},
{
IsoCode: "GBP",
Buy: 2.1184,
Sell: 2.1894
},
{
IsoCode: "USD",
Buy: 1.5781,
Sell: 1.6484
},
]

and my goal is to transform it into an object structured as follows:

    {
            USD: 
            {
              buy:1.5781,
              sell:1.6484,
    
            },
            EUR:
            {
              buy:1.948,
              sell:1.963,
            },
            GBP: 
            {
              buy:2.1184,
              sell:2.1894,
            }
          }

Currently, I am manually assigning the values, but I believe there must be a more efficient and scalable approach.

Answer №1

If I had to choose, I'd opt for using Object.fromEntries in combination with the object rest syntax:

const sorted = [{IsoCode: "EUR",Buy: 1.948,Sell: 1.963},{IsoCode: "GBP",Buy: 2.1184,Sell: 2.1894},{IsoCode: "USD",Buy: 1.5781,Sell: 1.6484},];

let res = Object.fromEntries(sorted.map(({IsoCode, ...rest}) => [IsoCode, rest]));

console.log(res);

Answer №2

If you want to make use of Array.prototype.reduce(), you can do so in the following way:

const sorted = [{
    Currency: "EUR",
    BuyPrice: 1.948,
    SellPrice: 1.963
  }, {
    Currency: "GBP",
    BuyPrice: 2.1184,
    SellPrice: 2.1894
  }, {
    Currency: "USD",
    BuyPrice: 1.5781,
    SellPrice: 1.6484
  },
]

const currencyObj = sorted.reduce(
  (acc, { Currency, BuyPrice, SellPrice }) => 
    (acc[Currency] = { Buy: BuyPrice, Sell: SellPrice }) && acc,
  {}
);

console.log(currencyObj);

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 is the best way to update only a portion of a nested schema in mongoose?

UPDATE: Through numerous trials, I finally discovered a successful method that converts any object into a format that mongoose can interpret. Take a look at the solution provided here: const updateNestedObjectParser = (nestedUpdateObject) => { cons ...

Subpar resolution of PNG images displayed in HTML canvas

My attempt to draw a PNG image onto the canvas is resulting in poor quality. I am using the drawImage method as shown below: src = folder+self.cur+".png"; imageObj.src = src; imageObj.onload = function() { context.clearRect(0, 0, cv, ch), context.drawImag ...

Managing Modules at Runtime in Electron and Typescript: Best Practices to Ensure Smooth Operation

Creating an Electron application using Typescript has led to a specific project structure upon compilation: dist html index.html scripts ApplicationView.js ApplicationViewModel.js The index.html file includes the following script tag: <script ...

Whenever I try to send an email in Node.js, I encounter 404 errors. Additionally,

I have an Angular application with a form that makes AJAX requests. Emailing works fine, but no matter what I set the response to, I get an error for the path '/send'. I assume Node.js expects the path '/send' to render a template or da ...

Error: Unable to execute workouts.map as a function in "React" due to a TypeError

This is the JSON data retrieved from the server: {workouts: Array(3)} workouts: Array(3) 0: {_id: 'idnumber1', title: 'pullup', reps: 40, load: '20', createdAt: '2022-07-20T18:06:39.642Z', …} 1: {_id: 'idnumb ...

Error: The variable YouTube has not been declared within this context / YouTube API

In my attempt to implement a search using the YouTube Data API, I have come up with the following code. The setup involves an express generated stack with jade. #player script. // 2. This code loads the IFrame Player API code asynchronously. ...

Resolved the time zone problem that was affecting the retrieval of data from the AWS Redshift database in Next

Currently utilizing Next.js for fetching data from AWS Redshift. When running a query from DataGrip, the results display as follows: orderMonth | repeatC | newC 2024-02-01 | 81 | 122 2024-01-01 | 3189 | 4097 However, upon retrieving the same query ...

Is there a way to automatically close one menu when another is opened by clicking?

When all other search results have failed to solve my issue, I resort to posting my own question. My problem involves opening hidden submenus in a website's main menu. However, when I open multiple submenus, they just stack above each other. Ideally, ...

Challenges faced when dealing with MongoDB and the latest version of webpack

Struggling to navigate MongoDB and React.js, encountering issues with MongoDB dependencies. Here are the dependencies listed in package.json: "dependencies": { "dotenv": "^16.3.1", "mongodb": "^4.1.0", &qu ...

Multi selection dropdown feature in Angular failing to populate the options

I am working on a small Angular controller that manages a dropdown menu, with the second dropdown menu populating based on the selection made in the first one. Despite my best efforts, I can't seem to populate the dropdown menus with any content from ...

Display event using Angular

I am currently working on an Angular project where I need to print a specific area of the page. While I know that this can be done using media CSS, it is causing issues for me due to the numerous print functionalities present in the project. I am attemptin ...

Utilize JSON data to display markers on Leaflet maps

I am exploring the world of Leaflet and I have a question about loading markers from a database into a leaflet map using PHP. In my PHP code, I extract latitude and longitude data from the database based on the selected ward and encode it in JSON format. ...

Getting the Right Value: A Step-by-Step Guide to Setting the Default or Selected Value in

When creating directive form controls (text, select, radio), I am passing a value to the directive function. If this value is not set or empty, then the default value should be taken from the question data._pageAttributes.defaultValue. HTML <div ng-re ...

How can you achieve the functionality of jQuery's hide() and show() in JavaScript?

Is there a JavaScript equivalent to my simple hide and show jQuery code? Here is my current code: $(document).ready(function() { $("#myButton").hide(); $("#1").click(function() { $("#myButton").show(); $("#myButton").click(function() { ...

modify an element using jquery

Hey there! I'm facing an issue where I have an ID of #item_quantity in a span, and I want it to refresh its contents once a button with the ID of #update_cart is clicked. It seems that everything else updates fine on click, but for some reason, the sp ...

Access within the identical window (PHP file) as opposed to an Iframe

I am currently working with a PHP file that retrieves data from my database. <?php $cdb = new PDO('mysql:dbname=xxx;host=localhost', 'xxx', 'xxx'); foreach ($cdb->query("SELECT * FROM images ORDER BY posted DESC LIMIT ...

Issue with Vuex not functioning properly in Nuxt.js

I'm facing an issue with setting the state in Vuex on my Nuxt.js App. It seems to not be working correctly. So, here is how I am trying to set the state using the fetch method: fetch({app, store, route}) { app.$axios.$get(`apps/${route.params ...

AngularJS: Share event from the parent component exclusively with its child components

I am looking to establish a way to broadcast an event from a parent directive to a specific child, without all children in every instance of the "parent" directive receiving it when using scope.broadcast in the parent directive link function. Current Beha ...

Following my ajax submission, the functionality of my bootstrap drop-down menu seems to have been compromised

I'm having an issue with my login page. After implementing Ajax code for the reset password feature, the dropdown menu on the login page doesn't work properly when wrong details are entered and the page reloads. I've tried using the $(' ...

"Utilizing an exported constant from a TypeScript file in a JavaScript file: A step-by-step guide

I am facing an issue when trying to import a constant from a TypeScript file into a JavaScript file. I keep encountering the error Unexpected token, expected ,. This is how the constant looks in the ts file: export const articleQuery = (slug: string, cate ...