如何在多个JSON对象中保存循环数据

时间:2019-05-15 17:44:30

标签: javascript json loops

我在循环中有一些变量,需要将其保存在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},
}

2 个答案:

答案 0 :(得分: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))

答案 1 :(得分:1)

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)