我有下面的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
}
]我可以像下面的json一样映射它,按fullName、startDate和endDate对对象进行分组,并添加一个包含endDate和motif的对象数组。
[
{
"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
}
]
}
]发布于 2021-02-03 03:58:04
如果我没理解错你的问题,你要找的东西如下:
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
}
]
}
})
}发布于 2021-02-03 04:11:08
您的示例输入和输出(交换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
}
]
}
]https://stackoverflow.com/questions/66016570
复制相似问题