问题描述:
今天在对接后台接口时,发现有一个接口数据不全,在不修改后端的前提下,如何拿到这些为null的数据呢,首先来看一下拿到的数据,结果都为null,但是又需要拿到这些数据展现到前端,那么怎么办呢
接口1查到的数据:
就在一筹莫展之际,我又发现了一个接口,根据doctorID查询医生的详细信息,可以发现这个接口能获取到数据,
接口2查到的数据:
我需要的数据:
然而我需要的数据是这个,那么只需要将第一个接口获取的数据中和第二个接口的数据拼接即可
解决方案:
因为两个接口都只能拿到部分的数据,所以我们需要将两份数据拼接起来
只需要拿到接口1中每一个JSON对象的doctorID,就可以利用这个doctorID查询到相对于的数据,进行动态的拼接,具体代码如下:
第一步:准备三个数组
//查询到的医生信息
orderDocotorList: [],
// 根据ID查询到的医生详细信息
orderDoctorIdList: [],
//拼接到的医生信息
orderDoctorConcatList: []
第二步,查询到接口一的数据存入orderDocotorList,并在SearchRegBsDoctorList()调用动态拼接函数
async SearchRegBsDoctorList() {
const data = {
locationId: parseInt(this.orderLocationId),
locationName: this.orderLocationRoom,
startDate: this.orderDate,
endDate: this.orderDate
}
try {
await order.SearchRegBsDoctorList(data).then(
response => {
console.log('我是SearchRegBsDoctorList,获取到:', response.data)
this.orderDocotorList = response.data
console.log("orderDocotorList" + JSON.stringify(this.orderDocotorList))
this.SearchBsDoctor()
}
)
} catch (error) {
console.log('Error:', error.message);
// 处理错误
}
},
第三步,使用for of遍历orderDocotorList,动态查询到接口二的数据并存入到数组 orderDoctorConcatList中
// 根据Id查询医生信息并拼接
async SearchBsDoctor() {
for (const doctorItem of this.orderDocotorList) {
const data = {
doctorID: doctorItem.DoctorId
}
console.log('for of遍历数组', doctorItem, doctorItem.DoctorId)
await order.SearchBsDoctor(data).then(
response => {
console.log(response.data)
this.orderDoctorIdList = response.data
// 将返回数据进行拼接
const orderConcatObject= {...doctorItem,...this.orderDoctorIdList}
// 将拼接完的数据存入一个新数组
this.orderDoctorConcatList.push(orderConcatObject)
}
)
}
console.log(this.orderDoctorConcatList)
}
至此,就已经将两组数据拼接完成了,控制台打印:
总结:
请注意在这里使用了ES6的拓展运算符...进行两个对象的拼接,注意:同时拷贝两个对象并拼接时,如果存在相同的属性,会产生覆盖,取后一个对象中的属性值,如name和age属性,且使用...拓展运算符拷贝为浅拷贝