skip to Main Content

I have this multidimensional 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"
}

And I want 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"
    }
]

The goal would be to adapt it for a Flatlist in react-native.
Been trying many tricks but nothing works. Any suggestions?

2

Answers


  1. On a first step you can map the array to the array you need

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

    And then simply sort by id

    result.sort((a, b) => a.id.localCompare(b.id));
    
    Login or Signup to reply.
  2. Using Object.keys(curr.rates) you get the IDs array and a following map and sort on it can achieve the desired result.

    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"
    };
    
    let result = Object.keys(curr.rates)
      .map(id => ({
        id,
        ...curr.rates[id]
      }))
      .sort((a, b) => Number(b.rate) - Number(a.rate));
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search