数组过滤基础问题

功能描述:点选标签,过滤显示列表内容。现将选中标签拼成一个数组,比如sId = ["1","2","3"],然后取出数据中 tag 数组中 id 等于 sId 数组中某一项的内容,取交集。

最后返回过滤后的 hotelList

1.选中标签数据:
const sId = ["1","2","3"]

2.列表数据:

data: {
    hotelList: [{
        "name": "A级房",
        "hotelRoomDetails": [{
          "price": 2360,
          "member": "0",
          "tag": [
            {
              "id": "1",
              "name": "95折"
            },
            {
              "id": "2",
              "name": "会员"
            },
            {
              "id": "3",
              "name": "88折"
            }
          ]
        }, {
          "price": 2560,
          "member": "1",
          "tag": [
            {
              "id": "1",
              "name": "含早"
            }]
        }]
      },
      {
        "name": "B房",
        "des": "58m² | 双床",
        "hotelRoomDetails": [{
          "price": 3390,
          "member": "1",
           "tag": [
            {
              "id": "1",
              "name": "含早"
            }]
        }, {
          "price": 3680,
          "member": "0",
          "tag": [
            {
              "id": "1",
              "name": "含早"
            },
            {
              "id": "2",
              "name": "会员价"
            }
          ]
        }]
      },
      {
        "name": "总统套房",
        "hotelRoomDetails": [{
          "price": 8990,
          "member": "0",
          "tag": null
        }]
      }
    ]
}

3.当前错误写法(map和filter混合使用):

    const filteredResults = this.data.hotelList.map(itemParent => itemParent.filter(itemChild => {
      return slectedPreId.includes(itemChild.hotelRoomDetails.preferential)
    }))
阅读 2.6k
4 个回答
this.data.hotelList.reduce((res, v) => {
    const hotelRoomDetails = v.hotelRoomDetails.filter(o => slectedPreId.includes(o.tag))
    if(hotelRoomDetails.length) res.push({...v, hotelRoomDetails})
    return res;
}, [])

ps:如果数据多,这个复杂度稍微有点高,可将slectedPreId先转为Set去查询是否包含

返回符合条件的hotelList:

const filteredResults = this.data.hotelList.filter(hotel => hotel.hotelRoomDetails.find(room => slectedPreId.includes(room.tag)))
this.data.hotelList.reduce((sum,curr)=>{
    let subDetails = curr.hotelRoomDetails.filter(it=>slectedPreId.findIndex(i=>i==it.tag)>-1);
    let cloneCurr = JSON.parse(JSON.stringify(curr));
    cloneCurr.hotelRoomDetails = subDetails;
    if (subDetails.length>0) sum.push(cloneCurr);
    return sum;
},[])
function getList(hotelList, yourTag) {
  return hotelList.filter(({ hotelRoomDetails }) =>
    hotelRoomDetails.some(({ tag }) => tag === yourTag)
  );
}

getList(data.hotelList, 2);

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