[英]object is sorted but its keys are not preserved using lodash sortBy
语境
需要使用 lodash 通过readingDate
对以下对象进行排序,我可以对其进行排序,但它的索引没有保留。
原装 JSON Object
{
"Inventory Creation": [
{
"id": 150,
"reading": "12345",
"readingDate": "2020-07-14"
}
],
"Inventory & Check-in": [
{
"id": 151,
"reading": "12345",
"readingDate": "2020-11-14"
}
],
"Check-in": [
{
"id": 152,
"reading": "12345",
"readingDate": "2020-08-14"
}
]
}
我试过的代码
_.sortBy(unsorted, o => o[0].readingDate).reverse();
这里unsorted
包含上述原始 JSON object
实际结果(我得到的)
{
0: [
{
"id": 151,
"reading": "12345",
"readingDate": "2020-11-14"
}
],
1: [
{
"id": 152,
"reading": "12345",
"readingDate": "2020-08-14"
}
],
2: [
{
"id": 150,
"reading": "12345",
"readingDate": "2020-07-14"
}
]
}
预期结果(我想要的)
{
"Inventory & Check-in": [
{
"id": 151,
"reading": "12345",
"readingDate": "2020-11-14"
}
],
"Check-in": [
{
"id": 152,
"reading": "12345",
"readingDate": "2020-08-14"
}
],
"Inventory Creation": [
{
"id": 150,
"reading": "12345",
"readingDate": "2020-07-14"
}
]
}
以下是步骤:
_.toPairs()
或内置的Object.entries()
)_.fromPairs()
或内置的Object.fromEntries()
) 下面的片段可以帮助你。 我使用_.chain()
以获得更好的可读性
const data = { "Inventory Creation": [ { id: 150, reading: "12345", readingDate: "2020-07-14", }, ], "Inventory & Check-in": [ { id: 151, reading: "12345", readingDate: "2020-11-14", }, ], "Check-in": [ { id: 152, reading: "12345", readingDate: "2020-08-14", }, ], } const res = _.chain(data).toPairs().sortBy((p) => p[1][0].readingDate).reverse().fromPairs().value() console.log(res)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.19/lodash.min.js"></script>
这是集合/数组的组合。 查看您正在使用的 lodash function 及其用途。 这不起作用,您正在尝试使用 Object 的数组函数。 function 做的正是它应该做的,对数组进行排序。 但是没有办法以这种方式创建排序的 object,它(意味着 lodash 函数)甚至不知道 object。
话虽如此,这是一个可行的解决方案(一般看一下 map/reduce):
const entries = Object.entries(unsortedArr);
const sorted = entries.sort((a,b) => a[1][0].readingDate < b[1][0].readingDate ? 1 : -1);
const reduced = sorted.reduce(
(acc, obj) => {
acc[obj[0]] = obj[1]
return acc},{});
Ofc 你可以链接这些调用,但我试图让它更容易理解。
我只是偶然发现了groupBy也可以使用。
这是一个蛮力解决方案。 首先对数组进行排序并存储键。 然后使用 sortedArray 中的键形成数组。
var sortedArray = _.sortBy(unsortedArray, function(val, key){
val[0].key = key;
return val[0].readingDate;
}).reverse();
var sortedArrayWithIndex = {};
_.each(sortedArray, function(val){
var key = val[0].key;
delete val[0].key;
sortedArrayWithIndex[key] = val;
});
console.log(sortedArrayWithIndex);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.