Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort array from object based on a property and return the sorted initial object

I have the following object

{
  "object": "list",
  "url": "/v1/prices",
  "has_more": false,
  "data": [
    {
      "id": "price_1KHlU72eZvKYlo2CblI51Z8e",
      "object": "price",
      "active": true,
      "billing_scheme": "per_unit",
      "created": 1642150211,
      "currency": "usd",
      "livemode": false,
      "lookup_key": null,
      "metadata": {},
      "nickname": null,
      "product": "prod_Kxgr3hZDfHnqu1",
      "recurring": {
        "aggregate_usage": null,
        "interval": "month",
        "interval_count": 1,
        "usage_type": "licensed"
      },
      "tax_behavior": "unspecified",
      "tiers_mode": null,
      "transform_quantity": null,
      "type": "recurring",
      "unit_amount": 2,
      "unit_amount_decimal": "2"
    },
    {...},
    {...}
  ]
}

How can I sort the object.data from it based on the unit_amount property and also keep the initial values of the object (url, has_more, …)?

I’ve tried using Ramda, but it’s giving me an new object just with the sorted data.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So I need object.data from the initial object to be sorted and to return the entire object after sorting.

>Solution :

Just simple sorting, for example

const obj = {
  "object": "list",
  "url": "/v1/prices",
  "has_more": false,
  "data": [
    {"unit_amount": 2,},
    {"unit_amount": 1,},
    {"unit_amount": 3,},
    {"unit_amount": 9,},
    {"unit_amount": 5,},
  ]
};

const newObj = { ...obj, data: obj.data.sort((o1, o2) => o1.unit_amount - o2.unit_amount) }; 

console.log(newObj)
.as-console-wrapper {max-height: 100% !important; top: 0}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading