Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

152
Vistas
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.

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

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Ramda will not make it easy for you to modify data, but if you want to create a copy of your input with a sorted copy of the array, that's pretty simple using the lens functions lensProp and over:

const sortData = over (lensProp ('data'), sortBy (prop ('unit_amount'))) 

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,} ]};

console .log (sortData (obj))
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.2/ramda.min.js"></script>
<script>const {over, lensProp, sortBy, prop} = R </script>

Here we steal the simple input format from Alexandr Belan. That answer already has some simple code. I think this is simpler -- and it's definitely more declarative -- but I wouldn't bother with it unless I was already using Ramda in my application.

about 4 years ago · Juan Pablo Isaza Denunciar

0

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}

about 4 years ago · Juan Pablo Isaza Denunciar

0

Objects in Javascript have no inherent order to their properties, whereas arrays do, so I suggest you extract the data array, sort it, then replace the unsorted version in your object. Something like this (object simplified for readability):

o = {
    "object": "list",
        "url": "/v1/prices",
            "has_more": false,
                "data": [
                    {
                        "id": "price_1KH",
                        "unit_amount": 12,
                    },
                    {
                        "id": "price_7QW",
                        "unit_amount": 3,
                    },
                    {
                        "id": "price_4DD",
                        "unit_amount": 7,
                    },
                ]
}
let data = o.data;
data.sort((x, y) => x.unit_amount - y.unit_amount);
o.data = data;
console.dir(o);
VM694:23 
Object
data: Array(3)
0: {id: 'price_7QW', unit_amount: 3}
1: {id: 'price_4DD', unit_amount: 7}
2: {id: 'price_1KH', unit_amount: 12}
length: 3
[[Prototype]]: Array(0)
has_more: false
object: "list"
url: "/v1/prices"
[[Prototype]]: Object
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda