Loading...

How to save loop data in multiple JSON objects


I have some variables in a loop, that are needed to be saved in a JSON. But need to make sure the next time loop iterates, the previously created JSON doesn't overwrite.

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
    }
  }
}

Required output is like this:

{
 "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},
}
- - Source

Answers

answered 1 week ago DJ Yadav #1

Try This:

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))

answered 1 week ago King Stone #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)

comments powered by Disqus