在javascript中匹配数组中的值

时间:2017-10-30 04:33:45

标签: javascript arrays node.js filter

我在数组中有一堆对象,格式如下:

[
  {
    "card_details": {
      "cardType": "gift"
    },
    "merchant_details": {
      "merchantName": "Walter Heisenberg1",
      "timeZone": "+05:30",
    }
  },
  {
    "card_details": {
      "cardType": "coupon",
      "cardTitle": "Coupon",
      "messageUser": "Hi",
      "punchCount": null,
      "messageReachPunchLimit": "Get your Freebie!",
      "merchantId": "59c214000e1a7825184cb813",
      "expiryDate": "21 Sep 2019",
      "discountPercent": "15",
      "cardImageUrl": ""
    },
    "merchant_details": {
      "merchantName": "Walter Heisenberg1",
      "timeZone": "+05:30"
    }
  },
  {
    "card_details": {
      "cardType": "punch",
      "cardTitle": "BlueM2",
      "messageUser": "Welcome!",
      "expiryDate": "21 Sep 2019",
      "punchCount": 25,
      "messageReachPunchLimit": "Get your Freebie!",
      "merchantId": "59c214000e1a7825184cb813",
      "cardImageUrl": "http://139.59.179.111/cloopapi/undefined"
    },
    "merchant_details": {
      "merchantName": "Walter Heisenberg1",
      "timeZone": "+05:30"
    }
  }
]

我想根据card_details对象中的cardType过滤对象。但我想从阵列中搜索。例如,如果我搜索["优惠券","礼物"],那么我应该获得所有具有card_details.cardType作为优惠券或礼物的卡片。 我需要能够在Node.js中做到这一点,即Javascript。

1 个答案:

答案 0 :(得分:3)

您可以在此处使用ES6 filterincludes功能:

collection.filter(item => ['coupon', 'gift'].includes(item.card_details.cardType))