【问题标题】:Unable to get information from Array无法从 Array 获取信息
【发布时间】:2019-11-22 06:46:06
【问题描述】:

```
function displayResults(responseJson) {
const gamedata = responseJson.results.map(game => {
	return {
		name: game.name,
		consoles: game.platforms,
		metacritc: game.metacritic,
		genre: game.genres
	};
});
console.log(gamedata);
inputData(gamedata);
}

function platformdata(consoles) {
return consoles.map(system => {
	return system.platform.name;
});
}

function inputData(gamedata) {
gamedata.map(input => {
	$(`#home-list`).html(`
	<h1>${input.name}</h1>
	<h5>${input.metacritc}</h5>
	<span>${input.system}</span>
	`);
});
}
```

我一直在尝试从数组中获取信息,但未能成功获取信息。游戏平台的信息有些嵌套,我一直在尝试挖掘它但无济于事。

https://api.rawg.io/api/games?page_size=1

我可以更详细地显示信息的最佳方式是建议将上面的链接扔给邮递员,你会看到我正在尝试使用什么。基本上它在结果>平台>平台>名称下。当我将此信息添加到地图函数中时,它会出现未定义。现在运行它,他们想出了用逗号说对象。我希望它只提供省略逗号的信息。我不知道如何让 join() 进入 html()。非常感谢!

编辑: 1)我想要的结果是能够在平台树内拉起但被埋没。如果我只使用 game.platforms 它会产生 [object, Object]。如果我尝试向 gamedata 中的行添加更多内容,它将产生 undefined。

2) 在 "gamedata.map(input => {" ?

3) 是的,我尝试根据我在网上找到的代码制作一个辅助函数。我在网上找到的代码使用了过多的li和ul

```
function platformnames(platforms) {
return platforms.map(system => {
	return '<li>'  system.platform.name + '</li>';
});
}

function pullArray(gamedata) {
gamedata.map(function(input) {
	let platformNames = input.platforms.map(
		system => `<li>${system.platform.name}</li>`
	);
	$(`#home-container`)
		.append(`<li><ul><li>${platformNames}</li></ul></li>`)
		.join(' ');
});
}
```

这行得通,但结果很奇怪。

4) 不,我将其全部添加到同一个 ID 中。

5) 那是我试图从 API 上的平台挖掘信息。它被埋在那里,我还没有找到一个好的解决方案。

function formatParams(params) {
    const queryItems = Object.keys(params).map(
        key => `${key}=${params[key]}`
    );
    console.log(queryItems);
    return queryItems.join('&');
}

const opts = {
    headers: {
        'User-Agent': `<ClassProject> / <VER 0.01> <Currently in Alpha testing>`
    }
};

function fetchAPI() {
    const params = {
        ...($('.search-param').val() && {
            search: $('.search-param').val()
        }),
        ...($('.genre-param').val() && {
            genres: $('.genre-param').val()
        }),
        ...($('.platforms-param').val() && {
            platforms: $('.platforms-param').val()
        }),
        ...($('.publishers-param').val() && {
            publishers: $('.publishers-param').val()
        }),
        page_size: '1'
    };

    console.log(params);

    const baseURL = 'https://api.rawg.io/api/games';
    const queryString = formatParams(params);
    let url = `${baseURL}?${queryString}`;

    console.log(url);

    fetch(`${url}`, opts)
        .then(response => response.json())
        .then(responseJson => displayResults(responseJson))
        .catch(error => {
            console.log(`Something went wrong: ${error.message}`);
        });
}

function displayResults(responseJson) {
    const gamedata = responseJson.results.map(game => {
        return {
            name: game.name,
            consoles: game.platforms,
            metacritc: game.metacritic,
            genre: game.genres
        };
    });
    console.log(gamedata);
    inputData(gamedata);
}

function inputData(gamedata) {
    let html = '';
    gamedata.forEach(input => {
        html += `<h1>${input.name}</h1>`;
        html += `<h5>Metacritic: ${input.metacritic ||
            'No metacritic rating'}</h5>`;
        html += 'Platforms:<br />';
        input.consoles.forEach(e => {
            html += `<span>${e.platform.name}</span><br />`;
        });
        html += `<br /><span>System: ${input.system}</span>`;
    });
    document.getElementById('home-list').innerHTML = html;
}

function pageLoad() {
    $(document).ready(function() {
        fetchAPI();
    });
}

pageLoad();

感谢大家的帮助,我已经很接近了。现在我返回“Metacritic:没有 metacritic 评级”,或者如果我删除它或部分未定义。我错过了什么?

【问题讨论】:

  • 你需要什么结果?请发布结果样本。
  • .map() 在不使用结果时不应使用。使用.forEach()
  • 另外你的gamedata在inputData函数中不包含input.system
  • 您正在为gamedata 的每个元素覆盖相同的DIV。
  • platformdata 函数有什么用?你永远不会叫它。

标签: javascript jquery postman api-design


【解决方案1】:

下面的 sn-p 为您提供平台名称。我修改/创建了

  • displayResults() 函数只返回一个值(并且还更正了 metacritic (metacritc -> metacritic) 中的错字)

  • inputData() 函数用于创建正确的 HTML 并将其附加到容器中

  • 一个fetchData()函数来实际获取数据

  • 用于启动获取和显示数据的未命名函数

您应该查看您的数据 - 您不使用 game.genres(尽管您映射它)并且您希望显示未映射的 input.system

function displayResults(responseJson) {
  return responseJson.results.map(game => {
    return {
      name: game.name,
      consoles: game.platforms,
      metacritic: game.metacritic,
      genre: game.genres
    };
  });
}

function platformdata(consoles) {
  return consoles.map(system => {
    return system.platform.name;
  });
}

function inputData(gamedata) {
  let html = ''
  gamedata.forEach(input => {
    html += `<h1>${input.name}</h1>`
    html += `<h5>Metacritic: ${input.metacritic || 'No metacritic rating'}</h5>`
    html += 'Platforms:<br />'
    input.consoles.forEach(e => {
      html += `<span>${e.platform.name}</span><br />`
    })
    html += `<br /><span>System: ${input.system}</span>`
  });
  document.getElementById('home-list').innerHTML = html

}

async function fetchData() {
  const data = await fetch('https://api.rawg.io/api/games?page_size=5')
  const json = await data.json()
  return json
}

(async function() {
  const json = await fetchData()
  inputData(displayResults(json))
})();
&lt;div id="home-list"&gt;&lt;/div&gt;

虽然它确实有效——你不应该在一个网站上使用多个h1 标签——这将是一个 HTML 验证警告(SEO!)。如果你每页只显示一个游戏,那就忘了我的话:)

【讨论】:

  • 谢谢!是的,我知道流派不被使用。它面临与平台相同的问题。我可以将平台逻辑用于未来的任何事件。我会将其转换为 jquery 并尝试使其运行。
  • 我认为你唯一需要转换的是document.getElementById()jQuery('#home-list').html(html) 会成功的(不用尝试就说出来:))
  • :D 我只会发送 :D,但我必须至少写 15 个字符
  • 现在我遇到了一个独特的问题。就是说每款游戏都没有metacritic评分。
  • 发生了一些变化。删除 || “没有 metacritic 评级”,你可能会看到更多。或 console.log 在 inputData() 中输入
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-24
  • 1970-01-01
  • 2016-12-13
  • 2019-10-03
  • 2013-04-29
  • 2015-12-20
  • 1970-01-01
相关资源
最近更新 更多