尝试创建一个数组,而不是在数组中创建一个数组

时间:2017-12-07 04:50:25

标签: javascript arrays

我正在尝试创建一个包含json文件信息的数组,如下所示:

  var jsonPages = ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches.json', '/page/total_pages', 'noHeaders');

  var clan1Id = [];
  var clan1Name= [];
  var clan2Id =[];
  var clan2Name = [];
  var skillLevel = [];
  var week = [];
  var map =[];

  for (var i = 1; i<=jsonPages; ++i) {
    clan1Id = clan1Id.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/clan1/id', 'noHeaders'));
    clan1Name = clan1Name.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/clan1/name', 'noHeaders'));
    clan2Id = clan2Id.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/clan2/id', 'noHeaders'));
    clan2Name = clan2Name.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/clan2/name', 'noHeaders'));
    skillLevel = skillLevel.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/division/tier', 'noHeaders'));
    week = week.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/week', 'noHeaders'));
    map = map.concat(ImportJSON('http://api.etf2l.org/competition/' + competitionId + '/matches/' + i + '.json', '/matches/maps', 'noHeaders'));
  }
  var array = [1, 2, 3, 4];

  Logger.log(array);
  Logger.log(clan1Id);

这是我得到Logs的输出:

[17-12-07 04:46:51:235 GMT] [1.0, 2.0, 3.0, 4.0]
[17-12-07 04:46:51:236 GMT] [[23565], [25693], [28116], [18707], [18974], [27513], [27219], [19058], [29798], [23483], [18974], [28078], [29771]]

如您所见,这会在数组中创建一个数组,我该如何解决?

1 个答案:

答案 0 :(得分:0)

根据ImportJSON中的文档,它返回一个二维数组(实际上是指一个数组数组,因为JS没有二维数组)。这可能是为了模仿电子表格数据的结构(列的行)。由于数组中的每个项目concat都是一个数组,因此您将获得该嵌套结构。

你需要压扁。 reduce可以提供帮助:

const importedJSON = ImportJSON(`http://api.etf2l.org/competition/${competitionId}/matches/${i}.json`, '/matches/clan1/id', 'noHeaders');
clan1Id = importedJSON.reduce((result, row) => result.concat(row), clan1Id);

...或者只是假设ImportJSON正在返回一行:

const url = `http://api.etf2l.org/competition/${competitionId}/matches/${i}.json`;
clan1Id = clan1Id.concat(ImportJSON(url, '/matches/clan1/id', 'noHeaders')[0])