【问题标题】:I would like to create a loop to browse each property of my object: this.current.questionnaireProfil JavaScript我想创建一个循环来浏览我的对象的每个属性: this.current.questionnaireProfil JavaScript
【发布时间】:2023-03-24 06:35:02
【问题描述】:

在我的文件中有我的代码:

for(var question in this.current.questionnaireProfil["p2"]){
    this.current=this.current.questionnaireProfil["p2"][question];
  }

在我的 console.log 中:

this.current.questionnaireProfil ={p1: {…}, p2: {…}, p3: {…}, p4: {…}, p5: {…}, …}

每次单击下一步时,我都想从 p1 转到 p2,从 p2 转到 p3,等等。

【问题讨论】:

  • 您的所有属性都标记为 p1...pn 吗?如果是这样,您可以简单地在之前定义一个字符串数组,并在您按下下一步时更新数组的索引。这将允许您拥有一个变量而不是如上所示的“p2”,并且在更新该变量时,您可以根据需要重新运行 for 循环
  • 我有一个 json 文件(不可编辑)
  • 谁看起来像:“Profil”:{“p1”:{“Q1”:{“intro”:“(请注意t...“intitule”:“家庭电话:”,“ args”:{“modalites”:{“1”:“numero fixe”}}}}},“p2”:{“Q2”:{“intitule”:“手机:”,“args”:{“modalites” : { "1" : "numero 便携" } } } },
  • 应该 p1 => 点击 => p2 => 点击 => p3.........
  • 好的,在这种情况下,您想遍历 JSON 对象 Iterating through JSON object 的所有键并将它们存储在数组中...然后您想设置一个处理程序以在单击时遍历数组 @ 987654322@

标签: javascript


【解决方案1】:

你可以create an array of the object's properties,然后保留一个索引,在这个索引中显示对象的属性:

var myObject = {
  questionnaire1: {
    1: "first",
    2: "second"
  },
  questionnaire2: {
    1: "first",
    2: "second",
    3: "third"
  },
  questionnaire3: {
    1: "first"
  }
};

// Create the array
var array = [];
for (property in myObject) {
  array.push(property);
}

var index = 0;
var out = document.getElementById("print");

function next() {
  var currentQuestionnaire = array[index % array.length];
  out.innerHTML = "myObject[" +
    currentQuestionnaire + "] contains " +
    Object.keys(myObject[currentQuestionnaire]).length + " questions";
  index++;
}
<button onclick="javascript:next();">Show next element</button>
<div id="print"></div>

【讨论】:

  • 否,因为如果我在第 5 组问题上,这是必要的;它给了我很多问题..
  • 我必须做一个循环,这样当我点击下一个时,我会转到下一个问题
  • this.current.questionnaireProfil(console.log 海报:{p1:{...},p2:{...},p3:{...},p4:{...},p5:{...}, …})
  • @JohnFitze 请再次检查我的答案。你没有定义最后一个元素应该发生什么,所以我将它编码为旋转(最后一个>第一个>第二个等)
  • 错误 /// for(var question in this.current.questionnaireProfil["p2"]){ this.current=this.current.questionnaireProfil["p2"][question]; }
【解决方案2】:
`for (var i in this.current.questionnaireProfil) {
if (this.current.questionnaireProfil.hasOwnProperty(i)) {
    console.log(i + " -> " + this.current.questionnaireProfil[key+1]);
};
}
for(var question in this.current.questionnaireProfil[i]){
this.current=this.current.questionnaireProfil[i][question];
}`

有了这个,我从 p1 转到 p32(这个小组问题的最后一个)。

【讨论】:

    猜你喜欢
    • 2017-09-05
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多