休息一段时间后,我一直在练习一些编码。我正在尝试从 api 过滤对象数组并创建一个函数,该函数将返回我发出请求的提取标题中的每个单词。
但是,当我想做过滤器时,它显示过滤器方法无法识别,并且我不知道如果您正在过滤从api调用的数组,它是否会受到影响。
这是代码。
function titles(word){
let sentence
let array = []
let api = 'https://jsonplaceholder.typicode.com/posts'
let data = fetch(api)
let response = data.then(res => res.json()).then(data => data.map((e) => { e.title}))
array = array.concat(response)
sentence = Promise.all(array.flat()).then(results => results.flat())
const people = sentence.filter(e => e.title.includes(word))
return people
}
但是,返回错误消息(见图)
但是当我对一组对象执行相同操作时,过滤器效果很好。
我感谢任何帮助、反馈和代码改进。预先感谢!
async
函数来处理 Promise 响应;data.map
函数的方式是错误的,它不返回对象数组Promise.all
功能;我的简化解决方案
async function titles(word = `sunt`){
let api = 'https://jsonplaceholder.typicode.com/posts';
let arr = await fetch(api).then(res => res.json());
// console.log(`array`, arr);
const peoples = arr.filter(obj => obj.title.includes(word));
// console.log(`peoples`, peoples);
return peoples;
}
// use TOP-Level await
const peoples = await titles(word = `sunt`);