【问题标题】:How to save loop data in multiple JSON objects如何将循环数据保存在多个 JSON 对象中
【发布时间】:2019-10-02 22:21:53
【问题描述】:

我在循环中有一些变量,需要保存在 JSON 中。但是需要确保下一次循环迭代,之前创建的 JSON 不会被覆盖。

try {
  ayats.forEach(function(element) {
    if (element.toLowerCase().includes(request.params.find.toLowerCase())===true)
    {
      counting++;
      element=JSON.parse(element);
      Surah_Name = element.SuratName;
      Ayat_No = element.AyatNo;
      x = "In Surah "+ element.SuratName+", Ayat Number: "+element.AyatNo+", Quran says: "+ element.Translation;

      // Here some logic to save Surah_Name, Ayat_No and x in JSON
    }
  }
}

需要的输出是这样的:

{
 "data1":{"Surah_Name": Surah_Name,"Ayat_No": Ayat_No, "x":x},
 "data2":{"Surah_Name": Surah_Name,"Ayat_No": Ayat_No, "x":x},
 "data3":{"Surah_Name": Surah_Name,"Ayat_No": Ayat_No, "x":x},
}

【问题讨论】:

  • 这个问题不太清楚。我们在这里讨论的是 JSON 对象还是 JSON 文件?
  • 你应该打印一个 JSON 对象数组,而不是 JSON 的 JSON
  • 改用 for 循环
  • 为什么要使用 data1data2...等对象和键,而不是将它们放在数组中并使用 data[1]data[2]
  • 不要在元素中设置数据,您应该在循环之前创建另一个变量,并在每次迭代中添加数据

标签: javascript json loops


【解决方案1】:

试试这个:

function getData(ayats){

const parentObj={};
let counting=0;
  ayats.forEach(function(element) {
    if (element.toLowerCase().includes(request.params.find.toLowerCase())===true)
    {
      counting++;
      element=JSON.parse(element);
      Surah_Name = element.SuratName;
      Ayat_No = element.AyatNo;
      x = "In Surah "+ element.SuratName+", Ayat Number: "+element.AyatNo+", Quran says: "+ element.Translation;
      const tempObj={
        Surah_Name,
        Ayat_No,
        x
      }
      parentObj[`data${counting}`]=tempObj
      // Here some logic to achieve the required output
    }
  })
  return parentObj;
}

console.log(getData(ayats))

【讨论】:

    【解决方案2】:
    var result = {};
    var counting = 0;
    
    ayats.forEach(function (element) {
      if (!element.toLowerCase().includes(request.params.find.toLowerCase())) return; //return means skip(continue)
      element = JSON.parse(element);
      Surah_Name = element.SuratName;
      Ayat_No = element.AyatNo;
    
      // Here some logic to achieve the required output
      result[`data${++counting}`] = {
        Surah_Name: Surah_Name,
        Ayat_No: Ayat_No,
        x: `"In Surah: ${Surah_Name} Ayat Number: ${Ayat_No} Quran says: ${element.Translation}`
      };
    })
    
    console.log(result)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多