我有一个包含两个计划对象的数组:
[ { "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",
}
我知道我可以映射到计划并筛选出正确的计划,但我如何单独返回正确的计划对象?
解决方案
您可以使用";Array.find";方法
示例
Stacklitz Snippet
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)
let obj = [ { "id": "price_aehdw424i7rxyeqiquedwuy",
"name": "Monthly Plan",
"price": 2900,
"interval": "month",
"currency": "usd",
},
{ "id": "price_46r34dgqn4d7w4fdw3476r323",
"name": "Yearly Plan",
"price": 29900,
"interval": "year",
"currency": "usd",
} ];
search_id = "price_aehdw424i7rxyeqiquedwuy";
let filtr = obj.filter(function(element){
if(element.id==search_id) return element
});
console.log (filtr.length?filtr[0]:'Not Found');