[英]how to iterate over two responses one after another using javascript
我用来自两个异步调用的两个响应初始化了一个变量,如下所示。
const items = await service.fetchDropdownFieldItems(payload.url);
它一个接一个地存储响应,并且工作正常。 这些响应如下:
1st response : [{id:1, value:'Shoe'},{id:2,value:'Boutique'},{id:3,value:'Clothing'}]
2nd response: {data:[{country_id:1, country_name:'Australia'},{country_id:2,country_name:'France'},{country_id:3,country_name:'USA'}]}
现在,我想格式化第二个响应的数据数组并用我的格式化响应替换第二个响应。
现在,如果我检查items变量,它应该包含这样
1st response : [{id:1, value:'Shoe'},{id:2,value:'Boutique'},{id:3,value:'Clothing'}]
2nd response: [{id:1, value:'Australia'},{id:2, value:'France'},{id:3, value:'USA'}]}
这样做的任何方法。 异步调用或 url 等没有问题。只有我想更改响应并替换为旧响应。
const formattedResponse = response.data.map((entry)=>({
id: entry.country_id,
value: entry.country_name
} ) )
您可以将此逻辑放置在service.fetchDropdownFieldItems中的某个位置,因此您无需在每次获取项目时手动更改数据
这是一个如何在获取 function 中使用它的示例。 如果您愿意,可以使用axios更改fetch
const formatResponse=(data)=>{
return data.map((entry)=>({
id: entry.country_id,
value: entry.country_name
} ) )
}
const fetchDropdownFieldItems =(url, options={})=>{
return fetch(url, options)
.then(res=> res.json())
.then(res=>res.data)
.then(formatResponse) //shorthand for .then(data=> formatResponse(data)
}
按如下方式使用它:
fetchDropdownFieldItems(...).then(doSomething)
//same as
fetchDropdownFieldItems(...).then(formattedData => doSomething(formattedData))
const processData = (response) => {
const dataArray = [];
response.data.forEach(({country_id,country_name})=>{
dataArray.push({ id: country_id, value: country_name });
})
return dataArray;
}
此答案与上一个答案相同,但执行时间更短,并且进行了一些优化
或也用作
const processData = (response) => {
return response.data.map(({country_id,country_name})=>({ id: country_id, value: country_name }))
}
[].map应该可以解决问题
const res2 = { data: [{ country_id: 1, country_name: 'Australia' }, { country_id: 2, country_name: 'France' }, { country_id: 3, country_name: 'USA' }] } const result2 = res2.data.map(v => ({ id: v.country_id, value: v.country_name })) console.log(result2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.