【问题标题】:How to filer an array of objects and return only one object based on a specific value如何过滤一组对象并根据特定值仅返回一个对象
【发布时间】:2022-07-22 22:32:03
【问题描述】:

我有一个包含两个计划对象的数组:

[ { "id": "price_aehdw424i7rxyeqiquedwuy", 
    "name": "Monthly Plan", 
    "price": 2900, 
    "interval": "month", 
    "currency": "usd",
  }, 
 { "id": "price_46r34dgqn4d7w4fdw3476r323", 
   "name": "Yearly Plan", 
   "price": 29900, 
   "interval": "year", 
   "currency": "usd",
 } ]

我要做的是使用一个值 (customerPlanId) 通过将其与 plan.id 匹配来找到正确的计划,然后返回正确的计划,如下所示:

{ "id": "price_aehdw424i7rxyeqiquedwuy", 
    "name": "Monthly Plan", 
    "price": 2900, 
    "interval": "month", 
    "currency": "usd",
  }

我知道我可以映射计划并筛选出正确的计划,但是我怎样才能自己返回正确的计划对象呢?

【问题讨论】:

标签: javascript object ecmascript-6


【解决方案1】:
const plan =  [ { "id": "price_aehdw424i7rxyeqiquedwuy", 
    "name": "Monthly Plan", 
    "price": 2900, 
    "interval": "month", 
    "currency": "usd",
  }, 
 { "id": "price_46r34dgqn4d7w4fdw3476r323", 
   "name": "Yearly Plan", 
   "price": 29900, 
   "interval": "year", 
   "currency": "usd",
 } ]

const filtered  = plan.find((x)=>x.id === yourId)

【讨论】:

    【解决方案2】:

    解决方案

    你可以使用“Array.filter”方法

    示例

    Stackblitz Snippet

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      • 2018-08-27
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      • 2021-09-01
      • 2021-02-26
      相关资源
      最近更新 更多