如何在javascript中将对象数组转换为数组对象?

Goo*_*mja 1 javascript arrays object

我正在尝试使用 javascript 将对象数组转换为数组对象。

这是代码

const data = [{
  yearMonthKey: "201907",
  dayKey: "15",
  startDate: "2019-07-15 00:00:00+0900",
  title: "testProgrma"
},
             {
  yearMonthKey: "201907",
  dayKey: "15",
  startDate: "2019-07-15 00:00:00+0900",
  title: "testProgrma"
},
            {
  yearMonthKey: "201907",
  dayKey: "16",
  startDate: "2019-07-15 00:00:00+0900",
  title: "testProgrma12313"
},
            {
  yearMonthKey: "201908",
  dayKey: "15",
  startDate: "2019-07-15 00:00:00+0900",
  title: "testProgrma"
}]

let programs = {};

Run Code Online (Sandbox Code Playgroud)

我想使用程序对象来制作一个对象,如下所示。

{
  201907: {
    15: [{
      yearMonthKey: "201907",
      dayKey: "15",
      startDate: "2019-07-15 00:00:00+0900",
      title: "testProgrma"
    },
        {
      yearMonthKey: "201907",
      dayKey: "15",
      startDate: "2019-07-15 00:00:00+0900",
      title: "testProgrma123132"
    }],
    16: [{
        yearMonthKey: "201907",
        dayKey: "16",
        startDate: "2019-07-15 00:00:00+0900",
        title: "testProgrma"
      }]
  },
    201908: {
      15: [{
        yearMonthKey: "201908",
        dayKey: "15",
        startDate: "2019-07-15 00:00:00+0900",
        title: "testProgrma"
      }]
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用数组方法中的映射来解决它。

data.map(item => {
  programs[item.yearMonthKey] : {
    programs[item.dayKey] : [{

    }]
  }
})
Run Code Online (Sandbox Code Playgroud)

但是将对象作为数组中相同dayKey键的值进行排序并将它们放在同一个yearMonthKey 中是有点挑战的。

adi*_*iga 5

你可以reduce阵列。将每个添加yearMonthKey到累加器。基于向对象yearMonthKey添加嵌套dayKeyacc[yearMonthKey]并将其默认为数组。

const data=[{yearMonthKey:"201907",dayKey:"15",startDate:"2019-07-15 00:00:00+0900",title:"testProgrma"},{yearMonthKey:"201907",dayKey:"15",startDate:"2019-07-15 00:00:00+0900",title:"testProgrma"},{yearMonthKey:"201907",dayKey:"16",startDate:"2019-07-15 00:00:00+0900",title:"testProgrma12313"},{yearMonthKey:"201908",dayKey:"15",startDate:"2019-07-15 00:00:00+0900",title:"testProgrma"}];

const output = data.reduce((acc, o) => {
  if (!acc[o.yearMonthKey]) 
    acc[o.yearMonthKey] = {};
    
  if (!acc[o.yearMonthKey][o.dayKey]) 
    acc[o.yearMonthKey][o.dayKey] = [];
    
  acc[o.yearMonthKey][o.dayKey].push(o);
  
  return acc;
}, {})

console.log(output)
Run Code Online (Sandbox Code Playgroud)