简体   繁体   English

在javascript中匹配数组中的值

[英]Matching for the Values in an array in javascript

I have bunch of objects in an array with format as below: 我有一堆对象,其数组的格式如下:

[
  {
    "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"
    }
  }
]

I want to filter the objects based on cardType in the card_details object. 我想根据card_details对象中的cardType过滤对象。 But I want to search from the array. 但是我想从数组中搜索。 For example, if I search for ["coupon","gift"], then I should get the all the cards which have the card_details.cardType as coupon or gift. 例如,如果我搜索[“ coupon”,“ gift”],则应该获取所有具有card_details.cardType的卡作为优惠券或礼物。 I need to be able to do this in Node.js,ie, Javascript. 我需要能够在Node.js(即Javascript)中执行此操作。

您可以使用ES6 filter并在此处includes功能:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM