A method for arranging an array of nested objects based on the objects' names

Recently, I received a complex object from an API:

let curr = {
    "base_currency_code": "EUR",
    "base_currency_name": "Euro",
    "amount": "10.0000",
    "updated_date": "2024-04-14",
    "rates": {        
        "USD": {
            "currency_name": "United States dollar",
            "rate": "1.0649",
            "rate_for_amount": "10.6489"
        },
        "AUD": {
            "currency_name": "Australian dollar",
            "rate": "1.6444",
            "rate_for_amount": "16.4443"
        },
        "CAD": {
            "currency_name": "Canadian dollar",
            "rate": "1.4669",
            "rate_for_amount": "14.6690"
        }
    },
    "status": "success"
}

I am now looking to transform this data into a sorted array of objects like this :

let curr = [
    {
        "id": "AUD",
        "currency_name": "Australian dollar",
        "rate": "1.6444",
        "rate_for_amount": "16.4443"
    },
    {
        "id": "CAD",
        "currency_name": "Canadian dollar",
        "rate": "1.4669",
       "rate_for_amount": "14.6690"
    },
    {
        "id": "USD",
        "currency_name": "United States dollar",
        "rate": "1.0649",
        "rate_for_amount": "10.6489"
    }
]

I have been attempting various methods to make it suitable for a Flatlist in react-native. However, I haven't had much luck so far. Any advice or suggestions would be greatly appreciated!

Answer №1

To start, you can transform the array into the desired format:

const updatedArray = [];
for(const [key, value] of Object.entries(curr.rates))
{
   const newData = {
      id : key,
      currency_name : …
   };
   updatedArray.push(newData);
});

Once the array is mapped properly, proceed to sort by id:

updatedArray.sort((a, b) => a.id.localCompare(b.id));

AUTHOR EDIT:

updatedArray.sort((a, b) => a.id > b.id ? 1 : -1);

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

Exploring the capabilities of AngularJS for efficient testing using Jasmine alongside mixpanel integration

Within my AngularJS application, I implement MixPanel for analytics by using the asynchronous script in my index.html file. index.html <script type="text/javascript">(function(e,b){if(!b.__SV){var a,f,i,g;window.mixpanel=b;a=e.createElement("script ...

On-page refresh triggering HTTP 404 error in Vue3 routing situation

Issue Upon reloading a route, such as /installer, in Vue3.js, I encounter the following error: Code Snippet I am utilizing the Router with the setup below: const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes, }); E ...

How can I trigger the execution of textarea HTML code with an onClick event using JavaScript?

When my fingers are lifted from the keyboard, some code will be automatically executed. I want to trigger this function when I click a button (onclick) instead of using onkeyup. <div id="result"></div> <textarea ...

It appears that the $http request is causing an endless $digest Loop

Looking to determine a user's status in my AngularJS app in order to display specific functionality content, here is the HTML code in my view: <span ng-show="authService.isSuperUser()">You are a Super User</span> To check if the user has ...

Is it possible to remove the "disabled" attribute using JS, but the button remains disabled?

There are two buttons on my page: the first one is currently disabled, and the second one is supposed to enable the first button. That's the plan. Button 1: $(document).ready(function() { $('#click').click(function() { document.getE ...

Having issues with my jQuery getJSON request. It's returning an empty response even though

I have been struggling to find a solution to this particular issue with no luck... Here is the jQuery getJSON request that I am working on: $.getJSON("http://localhost:8080/context/json/removeEntity.html", { contentId : 1, entIndex : entityIndex ...

"After executing a loop in JavaScript using jquery.ajax, the success function does not perform

Having trouble passing values from a PHP file to another function in Javascript. Even after a successful FOR LOOP, nothing seems to work within the SUCCESS block. Any suggestions? url1 = 'http://localhost:81/Dashboard/admin/inc/dashboard.php'; $ ...

The router.navigate() function seems to be malfunctioning as it is not working as

I have a method defined as follows: private redirect(path: string): void { this.router.navigate([path]); } This method is called within another method like so: private onError(error: any): void { switch (error.status) { case 401: / ...

What is the method to retrieve the string value from a JavaScript String object?

Is there a way to extend a method to the String prototype and manipulate the string value? I'm facing some difficulty in accessing the actual string value, as this, the current object context, seems to refer to the string object instead. String.pro ...

Deciphering Google geocode output in Java - unable to locate JSONArray[0] (even though it exists)

UPDATE: I have encountered a problem with integrating a direction service program into my geocode project. Despite the code working separately, when combined, it throws an error consistently. (Using Eclipse, Java EE, and Tomcat7) For your reference, below ...

Clicking through the button inside Vuetify's text-field append slot

While working on creating Vuetify's v-text-field with a slot named append containing a button, everything seems to be functioning correctly except for the fact that when I click the button, it goes through and focuses on the text field. On mobile devi ...

What is the solution for the error "BREAKING CHANGE: webpack < 5 used to automatically include polyfills for node.js core modules"?

I am trying to use the "web3" and "walletconnect/web3-provider" package in a Vue & Laravel 8 project. I have installed it using the npm i --save web3 @walletconnect/web3-provider command and then added the following code to import into ...

As the user types, the DD/MM/YYYY format will automatically be recognized in the

In my React component, I have an input box meant for entering a date of birth. The requirement is to automatically insert a / after each relevant section, like 30/03/2017 I am looking for something similar to this concept, but for date of birth instead of ...

Having an issue with the pop state function not functioning correctly

I am facing an issue with my images where clicking on a specific image changes the URL to that ID. However, I can only go back once and then the same URL is repeated every time I press the back button. Additionally, the forward button does not work at all. ...

Encountering Issue: Exceeding the number of hooks rendered in the previous render cycle

Every time I load my Nextjs page, an error message displays: "Error: Rendered more hooks than during the previous render." I attempted to fix this by adding if (!router.isReady) return null after the useEffect code. However, this caused a problem where th ...

What is the best way to change the location of a jQuery Mobile global popup?

I have a jQuery Mobile global popup that is initially empty and generated dynamically. I am utilizing the beforeposition event to detect when the popup opens. At this point, I load a configuration file or content file, create the content, and then add it t ...

Unable to adjust dimensions with CSS width and height properties

I'm currently working on developing an online game with a login screen inspired by Paper.io. I have created the username input and play button, but there seems to be an issue with the width and height specified in the CSS file for the input field. Eve ...

Is it possible to limit the values of parameters with react-router?

Currently, I am in the process of developing a website using react and react-router. I have two different types of routes set up, as shown below: <Route name="products" path="/:type/*" handler={ ProductList } /> <Route name="generic-template" p ...

When utilizing NavLink in React Router Dom for routing to an external link, a local host is automatically included in the prefix

I'm currently experiencing an issue with routing to an external link using React Router Dom 6.4. It seems that the localhost path is being appended to the URL. Can anyone provide insight on why this might be happening? localhost:3000/#/http://www.sav ...

Timer Does Not Appear to be Counting Down

I recently added a countdown clock to my website, but I'm having an issue with it not updating in real-time unless the page is refreshed. I'm not very familiar with javascript, so I found some code online and made some modifications myself to sui ...