如何从顺序不固定的custom_fields数组中提取指定字段值?
解决API返回custom_fields数组顺序不固定的取值问题
方案1:用Array.find()直接匹配取值
如果只需要单次提取个别字段,用find替代filter更合适——find会返回第一个匹配的对象,而非数组,直接就能提取value:
// 假设API返回的custom_fields结构 const custom_fields = [ { field_id: 1, name: 'name_ru', value: 'Иван' }, { field_id: 2, name: 'city_ru', value: 'Санкт-Петербург' }, // 其他自定义字段... ]; // 按field_id提取 const nameRu = custom_fields.find(item => item.field_id === 1)?.value; // 按name提取 const cityRu = custom_fields.find(item => item.name === 'city_ru')?.value;
- 用可选链
?.避免找不到匹配项时抛出Cannot read properties of undefined错误,此时会返回undefined。
方案2:转成映射对象(适合多次取值场景)
如果需要多次从custom_fields中提取不同字段,先把数组转成以name或field_id为键的映射对象,后续直接通过键名取值,无需重复遍历数组:
// 转成以name为键的映射 const fieldMapByName = custom_fields.reduce((map, item) => { map[item.name] = item.value; return map; }, {}); // 直接取值 const nameRu = fieldMapByName.name_ru; const cityRu = fieldMapByName.city_ru; // 或者转成以field_id为键的映射 const fieldMapById = custom_fields.reduce((map, item) => { map[item.field_id] = item.value; return map; }, {}); const nameRu = fieldMapById[1];
补充:关于filter的用法
如果一定要用filter,需要从返回的数组中取第一个元素再提取value,代码会稍显冗余:
const nameRu = custom_fields.filter(item => item.field_id === 1)[0]?.value;
内容的提问来源于stack exchange,提问作者JJJ
相关产品推荐
相关产品推荐

