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

Image not located: 404 error in JavaScript

I am currently working with JavaScript and have encountered an issue. I have an array of objects that contain various data such as id, title, price, and image. I need to retrieve this data from the array in order to display it. While I am able to successfu ...

Mastering the art of chaining promises in Mongoose

I need help figuring out how to properly chain promises for a "find or create" functionality using mongodb/mongoose. So far, I've attempted the following: userSchema.statics.findByFacebookIdOrCreate = function(facebookId, name, email) { var self = ...

confirm that the form is necessary and contains text

How can I ensure that a specific text string is validated for the input field labeled "promo"? Take a look at the code snippet below: <script> function validateForm() { var x = document.forms["myInquiry"]["promo"].value; if (x == null || x == "") ...

Transform the composer json file to a .php file

Could anyone help me figure out how to convert a script that is currently in composer json format into regular PHP files so I can use it on my shared hosting site? Unfortunately, my shared host doesn't support composer scripts. ...

Using Newtonsoft.Json for enum deserialization

Hello, I am having some trouble deserializing a class that contains an enum value: [JsonConverter(typeof(StringEnumConverter))] public enum MessageType { Verify, Disconnect, } [Serializable] public class SocketMessage { public Dictionary<S ...

issue encountered while passing a callback in a res.render() function

Currently, I am working on a small application where I am fetching data from remote JSON files to generate statistics that will be displayed in an EJS file later. My objective is to pass separate values for rendering and then utilize them within the EJS d ...

Utilizing JSON within browser cookies

I have encountered an issue where I need to store a JavaScript object in a cookie using JavaScript, but I am uncertain if this problem has been addressed previously. The core of my issue is that I have an HTML form with multiple input fields. I wish to ga ...

Serializing a sub object using GSON

I am currently facing a challenge with serializing this specific JSON structure : { "name":"name 1", "number":1, "standing":[ { "subRank":1, "subname":"test" }, { "subRank":2, "subname ...

The property of userNm is undefined and cannot be set

When attempting to retrieve a value from the database and store it in a variable, an error is encountered: core.js:6014 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'userNm' of undefined TypeError: Cannot set property &apos ...

ReactJS | Display or Conceal an Array of Objects depending on a specified condition

The Challenge: I am currently working on a task that involves hiding/showing react elements dynamically based on a property of the constructed Object. To be more specific, let's consider the Array of Objects below: const Apps = [ {name: App1, permi ...

Can you explain the concept of a framework operating "on top of" node.js in a way that would be easy for a beginner to understand?

If someone is new to JavaScript, how would you explain the concept of "on top of node.js" in simple programming language? I am looking for a general explanation as well as specific reference to Express on top of node.js in the MEAN stack. Appreciate your ...

The EJS template on the Express app is encountering an issue: it is unable to find the view "/id" within the views directory located at "/home/USER/Desktop/scholarship-app/views"

When attempting to render the request URL for an ID in my Express app, I encountered the following error: Error: Failed to find view "/id" in views directory "/home/USER/Desktop/scholarship-app/views" Here is a portion of my Express app code: app.get(&a ...

The function SVGGeometryElement.isPointInFill() may not function correctly in Chromium, but it does work properly in Firefox

I'm currently working on a solution to detect when a path within an SVG file on a canvas has been clicked. The code I've written functions correctly in Firefox, but I'm encountering issues with Chromium browsers. When I surround the code wit ...

Enhancing the appearance of specific text in React/Next.js using custom styling

I have a table and I am currently working on implementing a search functionality that searches for an element and highlights the search terms as they are entered into the search bar. The search function is functional, but I am having trouble with the highl ...

Issue: The type 'void' cannot be assigned to the type 'ReactNode' in the array.map() function

Having trouble with my function call error within the practice setup in App.tsx. My expectation of array.map() being compatible with TypeScript seems to be incorrect. The generated HTMLElement from this map is not displaying on screen. Any suggestions on ...

Using plain JavaScript, adding an element to an array by pushing the value of a string variable in an index position rather than pushing the

I have the following JavaScript code snippet: let array = []; const datas = [ 'name1', 'name2', 'name3', ]; async function getData() { datas.forEach((data) => { let myData = data.name; if(!array.include ...

What is causing npm to search for the package.json file in the incorrect directory?

I am currently working on a web application using TypeScript, Angular, and various dependencies. Of course, npm is also an essential part of the project. The package.json file was initialized in the project from the beginning using npm init, and it current ...

Using TypeScript to automatically determine the argument type of a function by analyzing the return type of a different function

I am working on an interface with the following structure: interface Res<R = any> { first?(): Promise<R>; second(arg: { response: R }): void; } However, I noticed that when creating a plain object based on this interface, the response ...

What is the method for determining profit as a percentage?

I need some help with a basic question. I have two variables, 'a' and 'b'. Variable A represents the money I receive from a customer, while variable B represents the money I will pay to a carrier. For example, if I receive $1000 from a ...

Working with JSON Requests using Python's GET and POST Methods

Currently immersed in the realm of automating dating applications, specifically focusing on a French app called Fruitz. I have successfully reverse engineered the API to obtain the necessary POST and GET sequences. Here is the function I'm currently ...