我正在尝试遍历 JSON 并按日期对其进行排序,这样我就可以看到从最晚到最旧的日期,然后将其写入文件。
这是我的代码
var reader = JSON.parse(fs.readFileSync('txt.json', 'utf8'));
function sortByDate(a, b) {
return new Date(a.lastUpdated).toJSON() - new Date(b.lastUpdated).toJSON();
}
reader.sort(sortByDate)
JSON 数据示例
{
"Data": {
"Contents": [
{
"Key": [
"HelloTest"
],
"lastUpdated": [
"2019-10-25T10:30:50.558Z"
]
},
{
"Key": [
"TestHello"
],
"lastUpdated": [
"2019-03-26T10:30:50.558Z"
]
}
]
}
}
最佳答案
以下是我在您的代码中发现的几个错误:
- 您的函数名称有错别字,它应该是
sortByDate
而不是sortbyDate
。 - 您需要对内部 json.Data.Contents 数组进行排序,而不是外部 json 对象。
- 您需要使用
lastUpdated[0]
引用您的lastUpdated
数组的第一个元素。 - 最后,您无需在排序函数中对日期对象调用
toJSON()
,只需转换为日期并返回差值即可。
您的内部数据字段也是数组,这对于 Key
和 lastUpdated
值来说似乎很奇怪。
如果您将字段保存为数组,下面是一个工作示例,展示了如何按日期对内部 Data.Contents
数组进行排序:
const jsonString = `{
"Data": {
"Contents": [{
"Key": ["HelloTest"],
"lastUpdated": ["2019-10-25T10:30:50.558Z"]
}, {
"Key": ["TestHello"],
"lastUpdated": ["2019-03-26T10:30:50.558Z"]
}]
}
}`;
function sortByDate(a, b) {
return new Date(a.lastUpdated[0]) - new Date(b.lastUpdated[0]);
}
const json = JSON.parse(jsonString);
const defaultValue = { Data: { Contents: [] } };
const sortedContents = [...(json || defaultValue).Data.Contents].sort(sortByDate);
const output = { ...json, Data: { Contents: sortedContents } };
console.log(output);
如果您将字段更改为标量,我建议这样做,这是另一个示例:
const jsonString = `{
"Data": {
"Contents": [{
"Key": "HelloTest",
"lastUpdated": "2019-10-25T10:30:50.558Z"
}, {
"Key": "TestHello",
"lastUpdated": "2019-03-26T10:30:50.558Z"
}]
}
}`;
function sortByDate(a, b) {
return new Date(a.lastUpdated) - new Date(b.lastUpdated);
}
const json = JSON.parse(jsonString);
const defaultValue = { Data: { Contents: [] } };
const sortedContents = [...(json || defaultValue).Data.Contents].sort(sortByDate);
const output = { ...json, Data: { Contents: sortedContents } };
console.log(output);
关于javascript - 如何按日期对 JSON 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57642626/