【问题标题】:expand and reorder an array of objects展开和重新排序对象数组
【发布时间】:2018-04-15 02:39:44
【问题描述】:

我有数组

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

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

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

    ...

我试过这个来扩展

它适用于扩展,但我无法按照我的意愿重新排序

【问题讨论】:

  • 在聊天中讨论这个?
  • 请先生...

标签: javascript arrays reactjs sorting data-structures


【解决方案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);

【讨论】:

  • dayindex 是一个可变的变量
  • dayindex 会在 0 到 10 之间变化,此处填写所需位置 dayindex 需要填写 {0 2 5 7 8 9 }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-30
  • 1970-01-01
  • 1970-01-01
  • 2012-08-16
  • 1970-01-01
相关资源
最近更新 更多