您可以使用replacer 参数并传入一个函数。可能有一种更简洁的方法可以做到这一点,但这是一个简单的例子:
const data = [{
date: new Date(),
id: 1
},
{
date: new Date(),
id: 2
}
]
const a = JSON.stringify(data)
const b = JSON.stringify(data, replacer('date'))
function replacer(target) {
return function(key, value) {
if (key == target) {
const month = new Date(value).getMonth()
return `Date month: ${month}`
}
return value
}
}
// [{"date":"2020-03-20T19:13:11.594Z","id":1},{"date":"2020-03-20T19:13:11.594Z","id":2}]
console.log(a)
// [{"date":"Date month: 2","id":1},{"date":"Date month: 2","id":2}]
console.log(b)
编辑
我的 TypeScript 装饰器功夫不是最强的,所以如果有人有任何建议,请随时指出改进。
作为装饰者:
@transformDate
class MyClass {
date: Date;
id: number;
constructor(date, id) {
this.date = date;
this.id = id;
}
}
function transformDate(target: any) {
const formatted = new Intl.DateTimeFormat("en", {
year: "numeric",
month: "short",
day: "2-digit"
}).format(this.date);
target.prototype.toJSON = function() {
return {
...this,
date: formatted
};
};
return target;
}
const data = [new MyClass(new Date(), 1), new MyClass(new Date(), 2)];
// [{"date":"Mar 20, 2020","id":1},{"date":"Mar 20, 2020","id":2}]
console.log(JSON.stringify(data));