【问题标题】:Matching for the Values in an array in javascript在javascript中匹配数组中的值
【发布时间】:2017-10-30 04:33:44
【问题描述】:

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

[
  {
    "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 过滤对象。但我想从数组中搜索。例如,如果我搜索 ["coupon","gift"],那么我应该得到所有具有 card_details.cardType 作为优惠券或礼物的卡片。 我需要能够在 Node.js 中执行此操作,即 Javascript。

【问题讨论】:

    标签: javascript arrays node.js filter


    【解决方案1】:

    你可以在这里使用 ES6 filterincludes 函数:

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

    【讨论】:

    • 在 ES5 中有没有办法做到这一点?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 2021-02-22
    • 1970-01-01
    相关资源
    最近更新 更多