我有和数组

    reservation1:[
      {name:"8:30",active:true,dayindex:1},
      {name:"jad",active:true,dayindex:3},
    ]


我需要将数组扩展到9
并使用名称为null的对象填充false false dayindex:顺序为0到10
所需的输出是

  output =[
   {name:"",active:false,dayindex:0}
   {name:"8:30",active:true,dayindex:1}

    ...


我试图扩大

它可以扩展,但是我想重新排序

最佳答案

您可以在添加其他元素后对数组进行排序:



var reservation = [
    {name:"8:30",active:true,dayindex:1},
    {name:"jad",active:true,dayindex:3},
    {name:"tony",active:true,dayindex:4},
    {name:"",active:false,dayindex:6}
];
var availabeDayIndex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].filter(el => !reservation.map(it => it.dayindex).includes(el));
var sortField = 'dayindex';
reservation = [...reservation, ...Array.from(Array(9 - reservation.length), (val, key) => ({name: null, active: false, dayindex: availabeDayIndex[key]}))].sort((a, b) => a[sortField] - b[sortField]);
console.log(reservation);

10-01 16:46