如何在JavaScript中根据指定属性列表获取对象子集?
嗨,这里有几个实用的方法帮你实现需求——把原数组里的对象筛选成只包含指定属性的新数组:
方法1:动态适配key列表(最灵活)
如果你的key列表是动态变化的,推荐用这种方法,不需要手动修改属性名:
const data = [ {name:"John", age:"22", weight:"60", height:"180cm"}, {name:"Emma",age:"25",weight:"55",height:"160cm"} ] const key = ["name", "weight", "height"] const result = data.map(item => key.reduce((newObj, currentKey) => { newObj[currentKey] = item[currentKey] return newObj }, {}) )
原理很简单:用map遍历原数组的每一个对象,再通过reduce把key列表里的属性逐个从原对象中取出,组装成新对象。后续key列表改了,代码完全不用动。
方法2:固定属性的简洁写法
如果你的key是固定不变的,直接用解构赋值会更简洁:
const data = [ {name:"John", age:"22", weight:"60", height:"180cm"}, {name:"Emma",age:"25",weight:"55",height:"160cm"} ] const result = data.map(({ name, weight, height }) => ({ name, weight, height }))
这里直接在map的回调函数里解构出需要的属性,然后返回一个新对象,一行搞定,可读性拉满。
方法3:封装成工具函数(适合重复使用)
如果这个需求你要在项目里多次用到,可以封装成一个通用工具函数,还能加个属性存在性检查,避免出现不必要的undefined:
const data = [ {name:"John", age:"22", weight:"60", height:"180cm"}, {name:"Emma",age:"25",weight:"55",height:"160cm"} ] const key = ["name", "weight", "height"] function pickObjectKeys(arr, keys) { return arr.map(item => { const newObj = {} keys.forEach(currentKey => { // 可选:只保留原对象存在的属性 if (item.hasOwnProperty(currentKey)) { newObj[currentKey] = item[currentKey] } }) return newObj }) } // 调用函数得到结果 const result = pickObjectKeys(data, key)
以上三种方法最终都会得到你想要的结果:
[ {name:"John", weight:"60", height:"180cm"}, {name:"Emma", weight:"55",height:"160cm"} ]
内容的提问来源于stack exchange,提问作者Panudeth Jaruwong
相关产品推荐
相关产品推荐

