基于键值获取JSON对象

问题描述 投票:0回答:1

此代码在获取和呈现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>`;
};
javascript arrays json fetch key-value
1个回答
0
投票

理想情况是使用GraphQL,因此您仅根据自己的条件获取所需的数据字段,在这种情况下,更改getListOfNames函数以仅当person.gender符合您的条件时输出一个人之间没有区别。只需将一个people.filter(根据您的条件的filterCallback)传递给它即可

© www.soinside.com 2019 - 2024. All rights reserved.