获取后端接口返回的数据中的部分字段
1、获取后端接口返回的数据中的部分字段
const isType = type => val => type === Object.prototype.toString.call(val).slice(8, -1)
const isArray = isType('Array')
const isObject = isType('Object')
// 后端返回的数据列表中字段可能并不全部需要
// 获取对象或者对象数组字段。举例:
// const obj = {name:'', age:123,school:{hh:11, kj:true}, asd:'qqwq'}
// getProps(obj, {name:'', school:{hh:''}, asd:''})
// ----> 得到其中部分字段。这个函数可以提升大量数据的渲染性能
const getProps = function (obj, props) {
if(!isObject(props)) {
throw new Error('参数有误,参数必须为object')
}
if(isArray(obj)) {
return obj.map(item => {
return Object.keys(props).reduce((prev, v) => {
prev[v] = isObject(props[v]) ? getProps(item[v], props[v]) : item[v] || ''
return prev
}, {})
})
}else if(isObject(obj)) {
return Object.keys(props).reduce((prev, item) => {
prev[item] = isObject(props[item]) ? getProps(obj[item], props[item]) : obj[item] || ''
return prev
}, {})
} else {
return obj
}
}
//====================普通对象使用方式=============================================
// 假设这个是后端接口返回数据
const obj = {
name: '张三',
age: '18',
school:'阿里斯顿',
company:{
name:'阿里巴巴'
},
customer:{
department: "总经办",
department_id: 23,
group: false,
login_time: "2020-09-07 15:28",
message: {customer:'asdasd', color:'#ccc'}
}
}
const newObj = getProps(obj, {
name:'',
company:'',
customer:{
department_id:'',
message:{customer:''}
}
})
console.log(newObj)
//====================对象数组使用=============================================
// 假设这个是后端接口返回数据
const obj2 = [obj, obj, obj]
const newObj2 = getProps(obj2, {
name:'',
company:'',
customer:{
department_id:'',
message:{customer:''}
}
})
console.log(newObj2)