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.
CodePudding user response:
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}
CodePudding user response:
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
