我是 lodash 的新手。我有一个 javascript 对象,如下所述。这样做的目的是探索/学习对象的有效过滤过程,特别是在数据庞大且嵌套的情况下。感谢您在这方面的指导。
JavaScript 对象是:
{
"Bus-1": {
"Seat1": {
"Bookings": {
"21032022": {
"BookedAt": "21/03/2022 3:43 PM",
"BookedBy": "Jon Doe"
},
"22032022": {
"BookedAt": "21/03/2022 9:43 PM",
"BookedBy": "James"
}
},
"Id": 1
},
"Seat2": {
"Bookings": {
"20032022": {
"BookedAt": "21/03/2022 3:43 PM",
"BookedBy": "Elijah"
},
"21032022": {
"BookedAt": "21/03/2022 3:43 PM",
"BookedBy": "Scott"
}
},
"Id": 2
},
"Seat3": {
"Bookings": {
"22032022": {
"BookedAt": "22/03/2022 02:41 AM",
"BookedBy": "Williams"
}
},
"Id": 3
}
},
"Bus-2": {
"Seat1": {
"Bookings": {
"22032022": {
"BookedAt": "22/03/2022 02:39 AM",
"BookedBy": "Lucas"
}
},
"Id": 1
}
}
}
从上面的集合中,对象层次结构如下图所示。
到目前为止我已经尝试过什么
loop...
Object to array and then array filter function which further leads to filtration again and again
Object to array and then lodash filter function which also cause nested filtration again and again in this case
我想要实现的目标:
So far what I have identified is looping and filtration slow the process when there is huge data. I am looking for an efficient method which return an object of all Bookings based on dates as mentioned below so that I can further validated if user has booking for same day or not.
"21032022": {
"BookedAt": "21/03/2022 3:43 PM",
"BookedBy": "Jon Doe"
},
"22032022": {
"BookedAt": "21/03/2022 9:43 PM",
"BookedBy": "James"
},
"20032022": {
"BookedAt": "21/03/2022 3:43 PM",
"BookedBy": "Elijah"
},
"21032022": {
"BookedAt": "21/03/2022 3:43 PM",
"BookedBy": "Scott"
},
"22032022": {
"BookedAt": "22/03/2022 02:41 AM",
"BookedBy": "Williams"
},
"22032022": {
"BookedAt": "22/03/2022 02:39 AM",
"BookedBy": "Lucas"
}
Regards, Aqdas
This:
_.assign(..._.flatMap(val, (seats, busKey) =>
_.flatMap(seats, (content, seatKey) =>
_.mapKeys(content.Bookings, (_, bookingKey) =>
`${busKey}_${seatKey}_${bookingKey}`))
))
Outputs this:
{
Bus-1_Seat1_21032022: {
BookedAt: "21/03/2022 3:43 PM",
BookedBy: "Jon Doe"
},
Bus-1_Seat1_22032022: {
BookedAt: "21/03/2022 9:43 PM",
BookedBy: "James"
},
Bus-1_Seat2_20032022: {
BookedAt: "21/03/2022 3:43 PM",
BookedBy: "Elijah"
},
Bus-1_Seat2_21032022: {
BookedAt: "21/03/2022 3:43 PM",
BookedBy: "Scott"
},
Bus-1_Seat3_22032022: {
BookedAt: "22/03/2022 02:41 AM",
BookedBy: "Williams"
},
Bus-2_Seat1_22032022: {
BookedAt: "22/03/2022 02:39 AM",
BookedBy: "Lucas"
}
}
Step-by-step:
flatMap
on val
to get the seats and key of the respective busflatMap
on the seats to get the content of each seat and its keymapKeys
on the bookings to avoid collisions on the final object. This is why we extracted the keys on each level. Assuming a valid input object, the keys will be unique.assign
扩展运算符将所有内容合并到一个对象中本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句