【发布时间】:2018-02-24 13:43:29
【问题描述】:
我需要使用 NodeJS 将各种结构化格式的信息转换为其他格式(例如 html 或文本)。所以我采用了基于 JSON-Schemas 将源格式转换为 JSON 的方法。我还可以根据 Pug 模板将生成的 JSON 转换为文本。
我现在正在寻找的是一种灵活的方式来标准化数据并简化 JSON 中的结构,因此例如日期和时间格式。
这样的对象的一个例子是:
{
header: {
sender: {
// more properties
id: '12345';
}
receiver: {
// more properties
id: '987654';
}
date: {
date: '170910',
time: '0922'
}
// more properties
}
// more properties
someMore: {
birthdate: {
year: 2016,
month: 5,
day: 11
}
otherProperty: {
// more properties
date: '20170205'
}
}
}
我想把它转换成
{
header: {
senderId: '12345',
receiverId: '987654'
date: '20170910T0922'
}
// more properties
someMore: {
birthdate: '20160511',
otherProperty: {
// more properties
date: '20170205'
}
}
}
这个想法是递归循环对象中的所有属性,并使用一个 Map,该 Map 对每个应该被操作的属性都有一个条目,例如
var map = new Map();
map.set('sender', getSender());
map.set('date', normalizeDate());
map.set('birthdate', normalizeDate());
为每个属性键检查映射,如果它返回一个函数,则执行该函数,否则 属性被创建,循环继续。
但是,我得到的明显印象是这个问题之前已经解决了,所以我想知道是否可以使用 npm 包来代替?
【问题讨论】: