假设我们有一个这样的对象-
const obj = { 0: { "time": 1, "day": 1, }, 1: { "time": 2, "day": 1, }, 2: { "time": 3, "day": 1, }, 3: { "time": 1, "day": 2, }, 4: { "time": 2, "day": 2, }, 5: { "time": 3, "day": 2, } };
我们需要编写一个JavaScript函数,该函数接受一个这样的对象,并将所有键值对分组在单独的子对象中,这些子对象的日键值相同。
输出结果
上述对象的输出应为-
const output = { '1': { '1': { time: 1, day: 1 }, '2': { time: 2, day: 1 }, '3': { time: 3, day: 1 } }, '2': { '1': { time: 1, day: 2 }, '2': { time: 2, day: 2 }, '3': { time: 3, day: 2 } } }
为此的代码将是-
const obj = { 0: { "time": 1, "day": 1, }, 1: { "time": 2, "day": 1, }, 2: { "time": 3, "day": 1, }, 3: { "time": 1, "day": 2, }, 4: { "time": 2, "day": 2, }, 5: { "time": 3, "day": 2, } }; const groupObject = obj => { let res = {}; res = Object.values(obj).reduce((acc, val) => { if(acc[val['day']] === undefined){ acc[val['day']] ={}; }; acc[val['day']][val['time']] = val; return acc; },{}); return res; }; console.log(groupObject(obj));
输出结果
控制台中的输出-
{ '1': { '1': { time: 1, day: 1 }, '2': { time: 2, day: 1 }, '3': { time: 3, day: 1 } }, '2': { '1': { time: 1, day: 2 }, '2': { time: 2, day: 2 }, '3': { time: 3, day: 2 } } }