我正在尝试转换
来源:
[{
dayIds: [1],
timeRanges: [{
end: 1200,
start: 800
}],
timezoneType: [{
timezone_type: "AM/PM"
}]
}, {
dayIds: [1, 2, 3],
timeRanges: [{
end: 720,
start: 360
}, {
end: 230,
start: 160
}],
timezoneType: [{
timezone_type: "AM/PM"
}, {
timezone_type: "AM/PM"
}, {
timezone_type: "AM/PM"
}]
}]
预期:
[{
dayIds: [1],
endTime: 1200,
startTime: 800,
timezone_type: "AM/PM"
}, {
dayIds: [1, 2, 3],
endTime: 720,
startTime: 360
timezone_type: "AM/PM"
}, {
dayIds: [1, 2, 3],
endTime: 230,
startTime: 160,
timezone_type: "AM/PM"
}]
我很难将上面的源数组转换为期望的平面数组,其中必须为每个timeRange对象构造新对象。
任何改进数组操作并解决上述问题的建议。
这是我到目前为止尝试过的。
let array = [{
dayIds: [1],
timeRanges: [{
end: 1200,
start: 800
}],
timezoneType: [{
timezone_type: "AM/PM"
}]
}, {
dayIds: [1, 2, 3],
timeRanges: [{
end: 720,
start: 360
}, {
end: 230,
start: 160
}, {
end: 230,
start: 160
}],
timezoneType: [{
timezone_type: "AM/PM"
}, {
timezone_type: "AM/PM"
}, {
timezone_type: "AM/PM"
}]
}]
var expected = [];
array.forEach(a=>{
a.timeRanges.forEach((tr,index)=>{
expected.push({days:a.dayIds,startTime:tr.start,endTime:tr.end,timezone_type:a.timezoneType[index].timezone_type});
});
});
console.log(expected)
答案 0 :(得分:1)
使用reduce
let arr = [{
dayIds: [1],
timeRanges: [{
end: 1200,
start: 800
}],
timezoneType: [{
timezone_type: "AM/PM"
}]
}
, {
dayIds: [1, 2, 3],
timeRanges: [{
end: 720,
start: 360
}, {
end: 230,
start: 160
}],
timezoneType: [{
timezone_type: "AM/PM"
}, {
timezone_type: "AM/PM"
}, {
timezone_type: "AM/PM"
}]
}]
arr = arr.reduce((acc, cur) => {
return [...acc, ...cur.timeRanges.map(timeRange => {
return {dayIds:cur.dayIds, timezone_type:cur.timezoneType[0].timezone_type, endTime:timeRange.end, startTime:timeRange.start}
})]
}, [])
console.log(arr)
答案 1 :(得分:1)
使用flatMap
并进行销毁。
const convert = (arr) =>
arr.flatMap(({ dayIds, timeRanges, timezoneType: [{ timezone_type }] }) =>
timeRanges.map((range) => ({ ...range, dayIds: [...dayIds], timezone_type }))
);
const data = [
{
dayIds: [1],
timeRanges: [
{
end: 1200,
start: 800,
},
],
timezoneType: [
{
timezone_type: "AM/PM",
},
],
},
{
dayIds: [1, 2, 3],
timeRanges: [
{
end: 720,
start: 360,
},
{
end: 230,
start: 160,
},
],
timezoneType: [
{
timezone_type: "AM/PM",
},
{
timezone_type: "AM/PM",
},
{
timezone_type: "AM/PM",
},
],
},
];
console.log(convert(data))