如何使用JavaScript过滤Json文件中的结果



如果在json文件中找不到标题,我会对如何显示错误感到困惑。这是我尝试过的一个代码。一切都很正常,但当我使用if(searchName!=todo.name(时,无论名称是写的还是错的,结果都只显示错误。请帮帮我,我会很感激的。

const list = document.getElementById('list');
const userAction = async (event) => {
event.preventDefault();
const searchName = document.getElementById('searchName').value.trim();
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => response.json())
.then(todos => {
todos.forEach((todo) => {
if(searchName == todo.title){
const li = document.createElement('li'); 
li.textContent = `${todo.userId} ${todo.id} ${todo.title} ${todo.completed}`;
list.appendChild(li);
} else if(searchName != todo.title)
{
const li = document.createElement('li');
list.textContent = `Search Result not found`;
list.appendChild(li);
}
});
})
}
<form method="POST">
<input type="text" id="searchName" class="form-control" placeholder="Lorem name">
<button  onclick="userAction(event)" class="search-icon"><img src="images/icon.png" alt="submit"></button>
</form>
<ul id="list">
</ul>
const td = todos
.filter(element => element.contain(searchName))
.map((todo) => {
const li = document.createElement('li'); 
li.textContent = `${todo.userId} ${todo.id} ${todo.title} ${todo.completed}`;
list.appendChild(li);
})
if(td.length <= 0) {
const li = document.createElement('li');
list.textContent = `Search Result not found`;
list.appendChild(li);
}

或者更奇特的方法:

const td = todos
.filter(element => element.contain(searchName))
.map((todo) => `${todo.userId} ${todo.id} ${todo.title} ${todo.completed}`)
if(td.length <= 0) {
td[0] = `Search Result not found`
}
td.forEach(t => list.append(`<li> ${t}</li>`))

类似的内容。

const list = document.getElementById('list');
const userAction = async (event) => {
event.preventDefault();
const searchName = document
.getElementById('searchName').value.trim();
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => response.json())
.then(todos => {
let result = todos
.filter((todo) =>
todo.title.includes(searchName));
while (list.firstChild) {
list.removeChild(list.firstChild);
}

if (result.length > 0) {
result.forEach(todo => {
const li = document.createElement('li'); 
li.textContent = `${todo.userId} ${todo.id} ${todo.title} ${todo.completed}`;
list.appendChild(li);
});
} else {
// not found.
}
});
}
<form method="POST">
<input type="text" id="searchName" class="form-control" placeholder="Lorem name">
<button  onclick="userAction(event)" class="search-icon"><img src="images/icon.png" alt="submit"></button>
</form>
<ul id="list">
</ul>

最新更新