js 数组对象处理

[
{backupType: "全备", weekCycle: 1, weekDay: 0, sequenceNumber: 1}
{backupType: "全备", weekCycle: 1, weekDay: 0, sequenceNumber: 2}
{backupType: "全备", weekCycle: 1, weekDay: 1, sequenceNumber: 2}
{backupType: "全备", weekCycle: 1, weekDay: 2, sequenceNumber: 3}
{backupType: "全备", weekCycle: 1, weekDay: 3, sequenceNumber: 3}
{backupType: "全备", weekCycle: 1, weekDay: 6, sequenceNumber: 3}
]

根据sequenceNumber,将数组分为三个部分,sequenceNumber一致的放在一块

[
{backupType: "全备", weekCycle: 1, weekDay: 0, sequenceNumber: 1}
{backupType: "全备", weekCycle: 1, weekDay: [0,1], sequenceNumber: 2}
{backupType: "全备", weekCycle: 1, weekDay: [2,3,6], sequenceNumber: 3}
]
阅读 3.3k
4 个回答
let data = [
  {backupType: "全备", weekCycle: 1, weekDay: 0, sequenceNumber: 1},
  {backupType: "全备", weekCycle: 1, weekDay: 0, sequenceNumber: 2},
  {backupType: "全备", weekCycle: 1, weekDay: 1, sequenceNumber: 2},
  {backupType: "全备", weekCycle: 1, weekDay: 2, sequenceNumber: 3},
  {backupType: "全备", weekCycle: 1, weekDay: 3, sequenceNumber: 3},
  {backupType: "全备", weekCycle: 1, weekDay: 6, sequenceNumber: 3}
]

let cache = {}
data = data.filter(item => {
  let num = item.sequenceNumber
  let weekDay = item.weekDay
  let tmp = cache[num]

  if (tmp) {
    let tmpWeekDay = tmp.weekDay
    if (Array.isArray(tmpWeekDay)) {
      tmpWeekDay.push(weekDay)
    } else {
      tmp.weekDay = [tmpWeekDay, weekDay]
    }
    return false
  } else {
    cache[num] = item
    return true
  }
})

我的思路:循环两次,外层拿到的对象作为参照对象,和内层循环到的对象依次做对比,找到一样的就拿到它的weekDay值push给参照对象,然后删除掉。

因为初始weekDay是number型,找到之后还要转换成数组才行。

    var arr = [
        { weekDay: 0, sequenceNumber: 1 }, 
        { weekDay: 0, sequenceNumber: 2 }, 
        { weekDay: 1, sequenceNumber: 2 }, 
        { weekDay: 2, sequenceNumber: 3 }, 
        { weekDay: 3, sequenceNumber: 3 }, 
        { weekDay: 6, sequenceNumber: 3 }
    ];
    for(let i = 0; i < arr.length; i++) {
        arr.map((m, n) => {
            if (arr[i].sequenceNumber === m.sequenceNumber && i !== n) {
                // 将参照对象的weekDay转换成数组
                arr[i].weekDay = [arr[i].weekDay]
                // 将该对象的weekDay值push到参照对象中,并删除
                arr[i].weekDay.push(m.weekDay)
                arr.splice(n, 1)
            }
        })
    }
    
    console.log(arr)
新手上路,请多包涵

arr1=arr.filter((entity)=>{entity.sequenceNumber==1});
arr2=....
以此类推,不写了

遍历数组,然后根据sequenceNumber的值push到不同的数组里面。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题