如何根据customerPlanId过滤对象数组并返回匹配的单个Plan对象
匹配Plan数组中指定ID的对象并返回
你可以直接使用数组的find()方法来实现,它会遍历数组并返回第一个符合匹配条件的对象,无需额外处理遍历结果:
示例代码
// 你的Plan数组 const plans = [ { "id": "price_aehdw424i7rxyeqiquedwuy", "name": "Monthly Plan", "price": 2900, "interval": "month", "currency": "usd" }, { "id": "price_46r34dgqn4d7w4fdw3476r323", "name": "Yearly Plan", "price": 29900, "interval": "year", "currency": "usd" } ]; // 要匹配的客户Plan ID const customerPlanId = "price_aehdw424i7rxyeqiquedwuy"; // 找到并返回匹配的Plan对象 const matchedPlan = plans.find(plan => plan.id === customerPlanId); console.log(matchedPlan);
说明
find()方法会逐个检查数组中的元素,一旦找到第一个满足plan.id === customerPlanId条件的对象,就会立刻返回该对象,不会继续遍历剩余元素,效率较高。- 如果数组中没有匹配的对象,
find()会返回undefined。
兼容旧环境的方案
如果你的运行环境不支持ES6的find()方法,可以使用普通for循环实现:
let matchedPlan = null; const customerPlanId = "price_aehdw424i7rxyeqiquedwuy"; for (let i = 0; i < plans.length; i++) { if (plans[i].id === customerPlanId) { matchedPlan = plans[i]; break; // 找到后跳出循环,避免多余遍历 } } console.log(matchedPlan);
内容的提问来源于stack exchange,提问作者herbie
相关产品推荐
相关产品推荐

