在对象数组中循环

时间:2019-10-10 04:29:34

标签: javascript jquery

我的代码需要一些帮助。这是一个jquery-bracket项目。

我有一个对象,里面有一个数组,我想循环一行数组,所以我不必手动生成这些行

var team = ["Team 1", "Team 2", "Team 3", "Team 4"];
var result = [1, 2, 2, 1];
var teams = "";
for (i = 0; i < team.length; i++) {
  teams += [`["${team[i++]}"`, ` "${team[i]}"], \n`]
}
var singleElimination = {
  "teams": [
    // line that I needed for loop
    [team[0], team[1]],
    [team[2], team[3]],
  ],
  "results": [
    [
      [
        // also line that I needed for loop
        [result[0], result[1]]
      ]
    ]
  ]
}
我试图将循环传递给变量并将其传递到数组中,但这似乎没有用。 对不起,我的英语不好,期待答案!

演示:https://quizzical-stonebraker-2d808a.netlify.com/

3 个答案:

答案 0 :(得分:0)

您可以简单地使用team.join(',');

例如:-

false

答案 1 :(得分:0)

var team = ["Team 1", "Team 2", "Team 3", "Team 4"];
var result = [1, 2, 2, 1];
var obj = {}
for(var i=0; i<team.length; i++){
 obj[team[i]] = result[i];
}

console.log(obj)

答案 2 :(得分:0)

var team = ["Team 1", "Team 2", "Team 3", "Team 4"];
var result = [1, 2, 2, 1];
var singleElimination = {
  teams: [
    // line that I needed for loop
    [team[0], team[1]],
    [team[2], team[3]]
  ],
  results: [
    [
      [
        // also line that I needed for loop
        [result[0], result[1]],
        [result[2], result[3]]
      ]
    ]
  ]
};
console.log("singleElimination", singleElimination);
var _teams = "";
singleElimination.teams.forEach(element => {
  element.forEach((team, index) => {
    _teams += element[index] + ", ";
  });
});
var _teamResults = "";
singleElimination.results.forEach(element => {
  element.forEach((team, index) => {
    _teamResults += element[index] + ", ";
  });
});
console.log("_teams", _teams);
console.log("_teamResults", _teamResults);