基于键值获取JSON对象



这段代码在获取和呈现JSON数组中的所有内容方面做得很好,但如果我只想列出具有特定键值(如性别(的对象呢?在提取或渲染过程中会发生这种情况吗?

const URL = "https://ghibliapi.herokuapp.com/people";
const main = document.getElementById("main");
main.innerHTML = "<p>Loading...";
fetch(URL).then((response) => response.json()).then((people) => main.innerHTML = getListOfNames(people));
const getListOfNames = (people) => {
const names = people.map((person) => `<li>${person.name} - ${person.gender} </li>`).join("n");
return `<ul>${names}</ul>`;
};

理想的情况是使用GraphQL,因此您只能根据您的条件获取所需的数据字段,在这种情况下,更改getListOfNames函数以在其person.gender与您的条件匹配时仅输出一个人,或者在获取所有后简单地向其传递一个经过过滤的人员数组,这两者没有区别

如果要返回筛选结果,则必须将api端点配置为接受筛选器。否则,将在渲染时进行过滤。

有了下划线,你就可以做_.where(response,{gender:'male'}(

最新更新