ReactJS中整理数组数据并推送到REST API的问题
需求:将指定产品相关props整理到products数组后推送到REST API
相关代码与问题场景
HTML结构
<div id="app" data-product="Premium Pack" data-sku="454677-rEqO3" data-image="https://2_RB_3183_006_71.jpg" data-website="https://website.com/" ></div>
当前冗余实现(逐个判断推送)
if( typeof this.props.product !== "undefined" ) data.push({ key : 'product', value : this.props.product }); if( typeof this.props.sku !== "undefined" ) data.push({ key : 'sku', value : this.props.sku }); if( typeof this.props.image !== "undefined" ) data.push({ key : 'image', value : this.props.image }); if( typeof this.props.website !== "undefined" ) data.push({ key : 'website', value : this.props.website });
尝试重构的问题版本
forEach写法(逻辑错误)
this.props.string.forEach( string => { let value = string.value; let name = string.name; if( typeof this.props.name !== "undefined" ) data.push({ key : name, value : value }); });
for...of写法(无法过滤指定props)
if( typeof this.props.product !== "undefined" ) { const obj = this.props; for (const [key, value] of Object.entries(obj)) { data.push({ key : key, value : value }); } }
核心诉求
替代当前逐个判断的冗余写法,精准将**指定的产品props(product/sku/image/website)**整理到products数组,再统一推送到API。
解决方案
方法1:定义指定props列表遍历筛选
通过预设需要收集的props名称列表,遍历检查每个prop是否存在,存在则添加到目标数组:
// 定义需要收集的产品props集合 const targetProps = ['product', 'sku', 'image', 'website']; const products = []; targetProps.forEach(propKey => { if (typeof this.props[propKey] !== 'undefined') { products.push({ key: propKey, value: this.props[propKey] }); } }); // 统一推送到API // api.send(products);
方法2:用Object过滤转换(更简洁)
先筛选出符合要求的键值对,再转换为目标格式数组:
const targetProps = ['product', 'sku', 'image', 'website']; // 筛选出存在的目标props const validProps = Object.entries(this.props).filter(([key]) => { return targetProps.includes(key) && typeof this.props[key] !== 'undefined'; }); // 转换为要求的{key, value}结构数组 const products = validProps.map(([key, value]) => ({ key, value })); // 推送到API // api.send(products);
优势说明
- 两种方法都通过指定props列表实现精准过滤,避免获取无关props
- 后续新增产品属性只需修改
targetProps数组,维护成本低 - 保留了原逻辑中“仅添加已存在props”的判断逻辑
内容的提问来源于stack exchange,提问作者Elichy
相关产品推荐
相关产品推荐

