创建一个在数组中具有相同键的新对象数组

时间:2017-07-19 22:41:43

标签: javascript arrays object

我有这个scheduleles数组,我需要它转换成这个输出。有线索吗?

let schedules = [
 {day: 'Sunday', time: '5:00 PM'},
 {day: 'Monday', time: '4:00 PM'},
 {day: 'Monday', time: '12:00 PM'},
 {day: 'Tuesday', time: '1:00 PM'}
]

let output = [
 {day: 'Sunday', time: '5:00 PM'},
 [
  {day: 'Monday', time: '4:00 PM'},
  {day: 'Monday', time: '12:00 PM'}
 ],
 {day: 'Tuesday', time: '1:00 PM'}
]

3 个答案:

答案 0 :(得分:1)



let schedules = [
 {day: 'Sunday', time: '5:00 PM'},
 {day: 'Monday', time: '4:00 PM'},
 {day: 'Monday', time: '12:00 PM'},
 {day: 'Tuesday', time: '1:00 PM'}
];
var temp = {};
schedules.forEach(function(ob){
   temp[ob.day] = temp[ob.day] === undefined ? ob : Array.isArray(temp[ob.day]) ? temp[ob.day].concat([ob]) : [temp[ob.day]].concat([ob]);
})
var output = Object.values(temp);

console.log(output);




答案 1 :(得分:1)

您可以先使用reduce()创建一个对象,然后使用map()来获取值数组。



let schedules = [
 {day: 'Sunday', time: '5:00 PM'},
 {day: 'Monday', time: '4:00 PM'},
 {day: 'Monday', time: '12:00 PM'},
 {day: 'Tuesday', time: '1:00 PM'}
]

var obj = schedules.reduce(function(r, e) {
  if (!r[e.day]) r[e.day] = e
  else r[e.day] = Array.isArray(r[e.day]) ? r[e.day].concat(e) : [r[e.day]].concat(e)
  return r;
}, {})

var result = Object.keys(obj).map(e => obj[e])

console.log(result)




答案 2 :(得分:0)

您可以使用Reduce with Object values

let schedules = [{
    day: 'Sunday',
    time: '5:00 PM'
  },
  {
    day: 'Monday',
    time: '4:00 PM'
  },
  {
    day: 'Monday',
    time: '12:00 PM'
  },
  {
    day: 'Monday',
    time: '3:00 PM'
  },
  {
    day: 'Tuesday',
    time: '1:00 PM'
  }
]


var value = schedules.reduce((acc, i) => {
  if (!acc[i.day]) {
    acc[i.day] = i
  } else if (Array.isArray(acc[i.day])) {
    acc[i.day].push(i);
  } else if (typeof acc[i.day] === 'object') {
    acc[i.day] = [acc[i.day]]
    acc[i.day].push(i)
  }

  return acc
}, {})

console.log(...Object.values(value))