[英]How can I map json to specific format in TypeScript?
我有以下 json
[
{
"fullName":"Mariem",
"startDate":"1917-04-25",
"endDate":"1917-04-26",
"endHour":"1330",
"motif":"maladie"
},
{
"fullName":"Mariem",
"startDate":"1917-04-25",
"endDate":"1917-04-26",
"endHour":"1800",
"motif":"renuion"
},
{
"fullName":"Mariem",
"startDate":"1917-05-25",
"endDate":"1917-05-25",
"endHour":"1600",
"motif":"renuion"
},
{
"fullName":"Jack",
"startDate":"0017-01-25",
"endDate":"0017-01-25",
"endHour":"1030",
"motif":null
}
]
谁可以我 map 它就像下面的 json 一样,按 fullName、startDate 和 endDate 对对象进行分组,并添加一个对象数组,包括 endDate 和主题。
[
{
"fullName":"Mariem ",
"startDate":"1917-04-25",
"endDate":"1917-04-26",
"data":[
{
"endHour":"1330",
"motif":"maladie"
},
{
"endHour":"1800",
"motif":"renuion"
}
]
},
{
"fullName":"Mariem ",
"startDate":"1917-05-25",
"endHour":"1917-05-25",
"data":[
{
"endHour":"1600",
"motif":"renuion"
}
]
},
{
"fullName":"Jack",
"startDate":"0017-01-25",
"endDate":"0017-01-25",
"data":[
{
"endHour":"1030",
"motif":null
}
]
}
]
如果我正确理解了您的问题,您正在寻找这样的东西:
interface SomeObj {
fullName: string,
startDate: string,
endDate: string,
endHour: string,
motif: string
}
interface Time {
endHour:string,
motif:string
}
interface MappedObj {
fullName: string,
startDate: string,
endHour: string,
data: Time[]
}
function mapToFormat(o: SomeObj[]): MappedObj[] {
return o.map(item => {
return {
fullName: item.fullName,
startDate: item.startDate,
endHour: item.endHour,
data: [
{
endHour: item.endHour,
motif: item.motif
}
]
}
})
}
您的示例输入和输出都有错误(交换endHour
和endDate
)。
这是一个快速的解决方案:
const map = new Map();
elements.forEach(item => {
const key = `${item.fullName}+${item.startDate}+${item.endDate}`;
if (!map.has(key)) {
map.set(key, {
fullName: item.fullName,
startDate: item.startDate,
endDate: item.endDate,
data: []
});
}
map.get(key).data.push({
endHour: item.endHour,
motif: item.motif
});
});
const result = Array.from(map.values());
输入:
const elements = [
{
"fullName":"Mariem",
"startDate":"1917-04-25",
"endDate":"1917-04-26",
"endHour":"1330",
"motif":"maladie"
},
{
"fullName":"Mariem",
"startDate":"1917-04-25",
"endDate":"1917-04-26",
"endHour":"1800",
"motif":"renuion"
},
{
"fullName":"Mariem",
"startDate":"1917-05-25",
"endDate":"1917-05-25",
"endHour":"1600",
"motif":"renuion"
},
{
"fullName":"Jack",
"startDate":"0017-01-25",
"endDate":"0017-01-25",
"endHour":"1030",
"motif":null
}
];
result
变量将具有以下值:
[
{
"fullName":"Mariem",
"startDate":"1917-04-25",
"endDate":"1917-04-26",
"data":[
{
"endHour":"1330",
"motif":"maladie"
},
{
"endHour":"1800",
"motif":"renuion"
}
]
},
{
"fullName":"Mariem",
"startDate":"1917-05-25",
"endDate":"1917-05-25",
"data":[
{
"endHour":"1600",
"motif":"renuion"
}
]
},
{
"fullName":"Jack",
"startDate":"0017-01-25",
"endDate":"0017-01-25",
"data":[
{
"endHour":"1030",
"motif":null
}
]
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.