gpt4 book ai didi

javascript - 向分组对象添加属性并取消分组

转载 作者:行者123 更新时间:2023-12-03 00:05:00 25 4
gpt4 key购买 nike

我正在使用 underscore.js 对我的对象进行分组,现在我想添加一个属性作为该组的标识符,然后将这些对象还原回其原始结构。但不知道该怎么做。

规则是查找当天谁有多个约会并向其添加属性。

我们在这里取得的成就:

https://jsfiddle.net/bjxgszmw/

使用这行代码:

var resultt = _.chain(allAppointments)
.groupBy('appointment_date')
.mapObject( date => _.groupBy(date, 'email' ) )

据我们所知,这是这样的:

{
"23July": {
"john@domain.com": [
{
"ap_id": 23,
"name": "John",
"email": "john@domain.com",
"appointment_date": "23July",
"appointment_category": 3,
"time": "morning"
},
{
"ap_id": 44,
"name": "John",
"email": "john@domain.com",
"appointment_date": "23July",
"appointment_category": 4,
"time": "afternon"
}
],
"rose@domain.com": [
{
"ap_id": 55,

像这样简单的事情;

allAppointments_Filtered: 
[{
"ap_id": 23,
"name": "John",
"email": "John@domain.com",
"appointment_date": "23July",
"appointment_category": 3,
"time": "morning",
hasMultipleAppointmentOnDate: "yes"

},{

"ap_id": 55,
"name": "Rose",
"email": "rose@domain.com",
"appointment_date": "23July",
"appointment_category": 4,
"time": "afternoon"
hasMultipleAppointmentOnDate: "nope"

},{

"ap_id": 44,
"name": "John",
"email": "john@domain.com",
"appointment_date": "23July",
"appointment_category": 4,
"time": "afternoon"
hasMultipleAppointmentOnDate: "yes"

},{
...

}];

最佳答案

嗯,您不需要进行所有这些分组和映射。您所要做的就是一张 map 和基于您检查的当前约会的计数:

var allAppointments = [
{
"ap_id": 23,
"name": "John",
"email": "john@domain.com",
"appointment_date": "23July",
"appointment_category": 3,
"time": "morning"
},
{
"ap_id": 55,
"name": "Rose",
"email": "rose@domain.com",
"appointment_date": "23July",
"appointment_category": 4,
"time": "afternon"
},
{
"ap_id": 44,
"name": "John",
"email": "john@domain.com",
"appointment_date": "23July",
"appointment_category": 4,
"time": "afternon"
},
{
"ap_id": 70,
"name": "Kate",
"email": "kate@domain.com",
"appointment_date": "29July",
"appointment_category": 4,
"time": "afternon"
}
]

var counts = {};
var result = _.mapObject(allAppointments, (appointment) => {
var key = appointment.email + appointment.appointment_date;

if (!_.has(counts, key)) {
counts[key] = _.countBy(allAppointments, (app) =>
appointment.email === app.email &&
appointment.appointment_date === app.appointment_date
).true > 1
}

appointment.hasMultipleAppointmentOnDate = counts[key];

return appointment;
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>

关于javascript - 向分组对象添加属性并取消分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54999039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com