根据先前对象数组中的共享属性创建新对象

时间:2018-07-16 13:35:30

标签: javascript arrays object grouping

我有一个包含“年”键和“日期”键的对象数组,如下所示:

    var fullDates = [
{ 'year': '2018', date: '2018-01'},
{ 'year': '2017', date: '2017-02'},
{ 'year': '2016', date: '2016-03'},
{ 'year': '2018', date: '2018-04'},
{ 'year': '2017', date: '2017-05' },
{ 'year': '2016', date: '2016-06'}
];

我想创建一个包含年份和日期的新对象数组,但其中的“ date”键是如下所示的数组。我该怎么办?

var final = [
{ 'year': '2018', date: ['2018-01', '2018-02']},
{ 'year': '2017', date: ['2017-03', '2017-04']},
{ 'year': '2016', date: ['2016-04', '2016-06']}
]

3 个答案:

答案 0 :(得分:1)

您可以使用Array.reduce()操作来获取输出:

var fullDates = [
  { 'year': '2018', date: '2018-01'},
  { 'year': '2017', date: '2017-02'},
  { 'year': '2016', date: '2016-03'},
  { 'year': '2018', date: '2018-04'},
  { 'year': '2017', date: '2017-05' },
  { 'year': '2016', date: '2016-06'}
];
var final = fullDates.reduce((acc, obj)=>{
  var existingObj = acc.find(item => item.year === obj.year);
  if(existingObj){
    existingObj.date.push(obj.date);
    return acc;
  }
  obj.date = [obj.date];
  acc.push(obj);
  return acc;
}, []);
console.log(final);

答案 1 :(得分:1)

您可以使用array#reduce

每年,创建一个包含objectyear属性的dates,并为每个重复的yeardate中添加array。然后从该object累加器中获取所有值。

const fullDates = [ { 'year': '2018', date: '2018-01'}, { 'year': '2017', date: '2017-02'}, { 'year': '2016', date: '2016-03'}, { 'year': '2018', date: '2018-04'}, { 'year': '2017', date: '2017-05' }, { 'year': '2016', date: '2016-06'} ],
    result = Object.values(fullDates.reduce((r, {year, date}) => {
      r[year] = r[year] || {year, dates : []};
      r[year].dates.push(date);
      return r;
    },{}));
console.log(result);

答案 2 :(得分:0)

希望这会有所帮助:

    var fullDates = [
{ 'year': '2018', date: '2018-01'},
{ 'year': '2017', date: '2017-02'},
{ 'year': '2016', date: '2016-03'},
{ 'year': '2018', date: '2018-04'},
{ 'year': '2017', date: '2017-05' },
{ 'year': '2016', date: '2016-06'}
];



const reducer = (accumulator, currentValue) => {

    let yearData = accumulator.find(x => x.year == currentValue.year);
    if(yearData !== undefined){
        yearData.date.push(currentValue.date);
    }
    else{
        accumulator.push({ 'year': currentValue.year, date: [currentValue.date]});
    }


    return accumulator;
}


var final = fullDates.reduce(reducer, []);