如何修改此函数以合并键的值?

时间:2016-11-24 11:02:41

标签: javascript object key concatenation

我想在对象“userName”中合并“year”键的值。

我有以下对象数组

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'
         },
        ];      

通过使用此功能,我可以根据loginName对偏差日期进行排序。所以在这种情况下,用户'jimmy'将只显示一次,但所有的devaiation日期和类型组合在一起。但是,键'year'的值只继承了第一个值并保持不变。如何合并密钥'year',以便用户'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);  
     }
    });

提前致谢!

1 个答案:

答案 0 :(得分:1)

您可以使用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)