如何将distinct()应用于对象数组RxJS?

Kis*_*ani 2 redux-observable rxjs6

我正在从 swagger pets API 中获取宠物列表。我想删除具有重复 id 的宠物,然后将其发送到 React 以避免重复密钥问题。我尝试了下面的代码,但对我不起作用。谁能帮我解决这个问题?

我是 RxJS 的新手,所以想删除基于宠物 ID 过滤不同对象的注释代码。

export function fetchPetEpic(action$) {
    return action$.pipe(
        ofType('GET_PETS'),
        switchMap(action => 
            ajax.getJSON(`https://petstore.swagger.io/v2/pet/findByStatus?status=${action.payload}`).pipe(
                map( response => response.map( (pet) => ({
                    id: pet.id,
                    pet: pet.pet
                }))),
                distinct( petList => petList.id),
                // map( petList => petList.filter((pet, index, list) => {
                //                     return list.map(petObj =>
                //                         petObj.id).indexOf(pet.id) === index;
                //                     })),
                map(response => petActions.setPets(response))
        )),
        catchError( error => ({ type: 'ERROR_PETS_FETCH', payload: error})),
    )
}
Run Code Online (Sandbox Code Playgroud)

假设 pets 数组类似于 [ { id: 1, pet: dog}, { id: 2, pet: cat }, { id: 3, pet: fish}, { id: 2, pet: rat }, { id : 4, 宠物: 鹦鹉}, { id: 1, 宠物: 猫头鹰 } ]

预期输出:[{ id: 1, pet: dog}, { id: 2, pet: cat }, { id: 3, pet:fish}, { id: 4, pet: parrot}]

我得到的输出与输入是相同的数组。

sen*_*ico 5

getJSON函数将返回一个发出一个项目(响应)并完成的 observable。(或者,它可以发出一个错误。)鉴于返回数组的快乐路径示例......

以下map运算符将接收反序列化的 JSON 数组并将其映射到新数组。也就是说,map运算符将恰好有一个输入事件并导致恰好一个输出事件。

map(response => response.map(pet => ({
  id: pet.id,
  name: pet.name,
  status: pet.status,
}))),
Run Code Online (Sandbox Code Playgroud)

distinct运营商在多个工作的事件。对于每个事件,它会过滤掉任何重复项(如您所指出的,重复项的定义可自定义)。以下distinct运算符将始终通过您的单个事件。另外,请注意这petList是一个数组。数组没有id属性,因此 lambda 将返回undefined。不过,lambda 返回什么并不重要。因为只有一个事件,所以它不会在任何比较中使用返回值。

distinct(petList => petList.id),
Run Code Online (Sandbox Code Playgroud)

看来您希望distinct处理数组的每个元素。为此,您可以使用from将数组转换为可观察对象并按concatMap顺序发出每个元素。随着多个事件流经管道,distinct可以发挥它的魔力:

...
concatMap(from), // shorthand for: `concatMap(response => from(response)),`
map(pet => ({
  id: pet.id,
  name: pet.name,
  status: pet.status,
})),
distinct(pet => pet.id),
...
Run Code Online (Sandbox Code Playgroud)

但是,此更改将导致发出多个 Redux 操作(每个不同的宠物一个)。reduce在发出 Redux 操作之前,我们可以使用运算符将每个不同的宠物累积回单个数组。

...
reduce((pets, pet) => [...pets, pet], []),
map(pets => petActions.setPets(pets)),
...
Run Code Online (Sandbox Code Playgroud)

让我们把它放在一起:

export function fetchPetEpic(action$) {
  return action$.pipe(
    ofType('GET_PETS'),
    switchMap(action =>
      ajax.getJSON(`https://petstore.swagger.io/v2/pet/findByStatus?status=${action.payload}`).pipe(
        concatMap(from), // shorthand for: `concatMap(response => from(response)),`
        map(pet => ({
          id: pet.id,
          name: pet.name,
          status: pet.status,
        })),
        distinct(pet => pet.id),
        reduce((pets, pet) => [...pets, pet], []),
        map(pets => petActions.setPets(pets)),
        catchError(error => ({ type: 'ERROR_PETS_FETCH', payload: error })),
      )
    ),
  )
}
Run Code Online (Sandbox Code Playgroud)

最后一个注意事项:您提供的示例数据和map您正在应用的数据之间存在一些差异。如果数组如下所示:

[ { id: 1, 宠物: 狗 }, ...

那么每个元素都没有nameorstatus属性,只有idandpet属性。也许以下是打算?

map(item => ({
  id: item.id,
  name: item.pet.name,
  status: item.pet.status,
})),
Run Code Online (Sandbox Code Playgroud)

或者可能只是您提供的示例数据有问题。无论哪种方式,我都建议仔细检查地图以确保它按预期投影您的值。