gpt4 book ai didi

javascript - 如何修改这个函数来合并键的值?

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

我希望将“year”键的值合并到“userName”对象中。

我有以下对象数组

userName=[{
loginName:'jimmy',
deviation:[{dates:[20150222,20150223,20150224,20150225], type:'vacation'}],
year:'2015'
},
{
loginName:'jimmy',
deviation:[{dates:[20150322,20150323,20150324,20150325], type:'sick'}],
year:'2016'
},
{
loginName:'chloe',
deviation:[{dates:[20150222,20150221,20150224,20150225], type:'national free day'}],
year:'2016'
},
];

通过使用此函数,我可以根据登录名对偏差日期进行排序。因此,在这种情况下,用户“jimmy”将仅显示一次,但所有偏差日期和类型都会合并。然而,关键“年份”的值仅继承第一个值并保持不变。如何通过修改我当前的函数来合并键“年份”,以便用户“吉米”年份将显示“2015,2016”:

var mergedUsername = [];

userName.forEach(function(deviation) {
var existing = mergedUsername.filter(function(v, i) {
return v.loginName == deviation.loginName;
});
if(existing.length) {
var existingIndex = mergedUsername.indexOf(existing[0]);
mergedUsername[existingIndex].deviation = mergedUsername[existingIndex].deviation.concat(deviation.deviation);
} else {
if(typeof deviation.deviation == 'string')
deviation.deviation = [deviation.deviation];
mergedUsername.push(deviation);
}
});

提前致谢!

最佳答案

您可以使用reduce()来获得所需的结果。

var data = [{
loginName: 'jimmy',
deviation: [{
dates: [20150222, 20150223, 20150224, 20150225],
type: 'vacation'
}],
year: '2015'
}, {
loginName: 'jimmy',
deviation: [{
dates: [20150322, 20150323, 20150324, 20150325],
type: 'sick'
}],
year: '2016'
}, {
loginName: 'chloe',
deviation: [{
dates: [20150222, 20150221, 20150224, 20150225],
type: 'national free day'
}],
year: '2016'
}];

var o = {}
var result = data.reduce(function(r, e) {
if (!o[e.loginName]) {
o[e.loginName] = e;
r.push(o[e.loginName]);
} else {
o[e.loginName].deviation[0].dates.push(...e.deviation[0].dates)
o[e.loginName].deviation[0].type += ' ' + e.deviation[0].type
o[e.loginName].year += ' ' + e.year
}
return r;
}, [])

console.log(result)

关于javascript - 如何修改这个函数来合并键的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40784729/

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