在实际开发中,经常要用map函数返回一些新的objectArray,
常见的有两种需求:
- 只要返回想要的key
- object key太多,就要反过来,移初不需要的key。
故简单抽离封装到utils中,如果在map函数中要处理的逻辑过多,如返回新的key,过多的条件处理等不在此考虑。
const goods=[
{
id:1,
name:'item1',
price:99,
discount:9.7
},
{
id:2,
name:'item2',
price:88,
discount:9
},
{
id:3,
name:'item3',
price:108,
discount:8.8
},
]
/**
* params {Array} arr
* params {Array} props
* return ObjectArray only container keys in props
*/
const pickKeys=function(arr,props){
if(!Array.isArray(arr)){
return new Error('arr must be an array')
}
if(!Array.isArray(props)){
return new Error('props must be an array')
}
return arr.map((item)=>{
let newItem={}
for(key in item){
if(props.indexOf(key)>-1){
newItem[key]=item[key]
}
}
return newItem
})
}
const easyGoods=pickKeys(goods,['id','price','noKey'])
log(easyGoods)
/**
* params {Array} arr
* params {Array} props
* return ObjectArray than has removed keys in props
*/
const removeKeys=function(arr,props){
log(props)
if(!Array.isArray(arr)){
return new Error('arr must be an array')
}
if(!Array.isArray(props)){
return new Error('props must be an array')
}
return arr.map((item)=>{
for(key in item){
if(props.indexOf(key)>-1){
delete item[key]
}
}
return item
})
}
//处理后的数据发给请求,该数据不需要name属性
let postData=removeKeys(goods,['name']
log(postData)