【发布时间】:2022-01-14 19:07:51
【问题描述】:
我有以下对象
{
"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"
},
{...},
{...}
]
}
如何根据 unit_amount 属性对 object.data 进行排序,同时保留对象的初始值(url、has_more、...) ?
我尝试过使用 Ramda,但它给了我一个新对象,其中包含已排序的数据。
所以我需要对初始对象中的 object.data 进行排序,并在排序后返回整个对象。
【问题讨论】:
-
obj.data.sort(comparison_function) -
sort修改数组,因此对data数组进行排序不会对其他属性产生任何影响。 -
@Barmar 是的,但它没有从初始对象返回其余的道具
-
试试这个方法
const newObj = { ...obj, data: obj.data.sort((o1, o2) => o1.unit_amount - o2.unit_amount) };
标签: javascript arrays sorting ramda.js