如何从对象数组中筛选指定name对应的strength属性值
筛选多个指定name对应的strength属性值
需求
从给定的JavaScript对象数组中,提取name为pachio和hunter的所有strength属性值,期望输出:['cool kids', 'suck bloods']
原代码
const array = [{ name: 'pachio', strength: 'cool kids' }, { name: 'hunter', strength: 'suck bloods' }, { name: 'chloyi', strength: 'cute' }] const result = array.filter(function(getName) { return getName.name == 'pachio'; /*This_need_to_be_fix*/ }); const result2 = result.map((getStrength) => getStrength.strength); console.log(result2) /*cool kids*/
修改方案
只需修改filter的判断逻辑,用数组includes()方法检查当前对象的name是否在目标列表中即可,还可通过链式调用简化代码:
方案1:调整原filter逻辑
const array = [{ name: 'pachio', strength: 'cool kids' }, { name: 'hunter', strength: 'suck bloods' }, { name: 'chloyi', strength: 'cute' }] // 定义需要匹配的name列表 const targetNames = ['pachio', 'hunter']; const result = array.filter(function(item) { // 检查当前item的name是否在目标列表内 return targetNames.includes(item.name); }); const result2 = result.map(item => item.strength); console.log(result2) // 输出: ['cool kids', 'suck bloods']
方案2:链式调用简化代码
const array = [{ name: 'pachio', strength: 'cool kids' }, { name: 'hunter', strength: 'suck bloods' }, { name: 'chloyi', strength: 'cute' }] const targetNames = ['pachio', 'hunter']; const result = array .filter(item => targetNames.includes(item.name)) .map(item => item.strength); console.log(result) // 输出: ['cool kids', 'suck bloods']
说明
Array.includes()能高效判断当前name是否属于目标集合,后续新增或修改需要匹配的name时,只需调整targetNames数组即可,比多个||拼接的判断更易维护。- 链式调用
filter+map的写法可减少中间变量,让代码更简洁紧凑。
内容的提问来源于stack exchange,提问作者Badrul Hanif
相关产品推荐
相关产品推荐

