使用.filter和.reduce

时间:2018-07-24 03:34:26

标签: javascript object filter reduce

我有这个诊所的对象,密钥是诊所的ID,并且它具有ID和邀请:

const clinics = {
    "a0CW0000001K2F8MAK": {
        "id": "a0CW0000001K2F8MAK",
        "invitations": {
            "56205": {
              "id": "56205",
              "status": "Confirmed",
          },
        }
    },
    "a0CW00000026gjsMAA": {
        "id": "a0CW00000026gjsMAA",
        "invitations": {}
    },
    "a0CW00000026gjTMAQ": {
        "id": "a0CW00000026gjTMAQ",
        "invitations": {
            "56445": {
              "id": "56445",
              "status": "Cancelled",
          },
        }
    },
    "a0CW00000026gipMAA": {
        "id": "a0CW00000026gipMAA",
        "invitations": {
            "56447": {
                "id": "56447",
                "status": "Confirmed",
            },
            "56448": {
                "id": "56448",
                "status": "Cancelled",
            },
            "56456": {
                "id": "56456",
                "status": "Declined",
            }
        }
    },
    "a0CW00000026gjOMAQ": {
        "id": "a0CW00000026gjOMAQ",
        "invitations": {}
    },
    "a0CW00000026gjnMAA": {
        "id": "a0CW00000026gjnMAA",
        "invitations": {
          "56304": {
              "id": "56304",
              "status": "Pending",
          },
        }
    },
}

并且我只想在邀请->状态等于“已取消”的情况下才返回该对象,所以可能有多个邀请,并且如果取消任何邀请,则需要返回该对象。情况下,返回:

const clinics = {
    "a0CW00000026gjTMAQ": {
        "id": "a0CW00000026gjTMAQ",
        "invitations": {
            "56445": {
              "id": "56445",
              "status": "Cancelled",
          },
        }
    },
    "a0CW00000026gipMAA": {
        "id": "a0CW00000026gipMAA",
        "invitations": {
            "56447": {
                "id": "56447",
                "status": "Confirmed",
            },
            "56448": {
                "id": "56448",
                "status": "Cancelled",
            },
            "56456": {
                "id": "56456",
                "status": "Declined",
            }
        }
    },
}

我尝试了类似的方法,但是没有用:

function filterByStatus(clinics) {
  return Object.keys(clinics)
    .filter(clinicId => clinics[clinicId].invitations.status === "Cancelled")
    .reduce((acc, key) => Object.assign(acc, { [key]: clinics[key] }), {});
}

我该怎么做?谢谢!

1 个答案:

答案 0 :(得分:2)

检查some对象invitations中的values是否具有status的{​​{1}}。不需要Cancelled,只需在filter函数本身中进行测试,就可以避免重复两次:

reduce