jeudi 3 juin 2021

fetching data oustide the map function using javascript / node js

let object = [
  {
    id: '01',
    name: 'Subject',
    'Data.type': 'maths',
  },
  {
    id: '02',
    name: 'Subject',
    'Data.type': 'science',
  },
  {
    id: '04',
    name: 'language',
    'Data.type': 'node',
  },
  {
    id: '05',
    name: 'language',
    'Data.type': 'node',
  }
  /*...*/
];

let type=[];
let result=[];
object.map(async (value) => {
  type.push(value["Data.type"]);
  if(some condition){
  // 1st condition
   if(some condition){
    // 2nd condition
     if(some condition){
      let path= await functionName();
      // 3rd conditon
      if(some condtion){
      // 4th condition
      result.push("task");
     }
    }
   }
  }
  // I can fetch result till here console.log(result)
});
// i can't fetch result here and i can't put condtion here as data present inside dObject is dummy for refrence purpose only
console.log(type);
console.log(result);

I declare two array outside the map function i can fetch name array easily but can't fetch result array i don't know why but its scope get ended inside the map function is there any other way i can fetch result outside the map function

  • for reference i am posting my name function which work fine
let object = [
  {
    id: '01',
    name: 'Subject',
    'Data.type': 'maths',
  },
  {
    id: '02',
    name: 'Subject',
    'Data.type': 'science',
  },
  {
    id: '04',
    name: 'language',
    'Data.type': 'node',
  },
  {
    id: '05',
    name: 'language',
    'Data.type': 'node',
  }
];

let type=[];
let result=[];
object.map(async (value) => {
  type.push(value["Data.type"]);
});
// i can't fetch result here and i can't put condtion here as data present inside dObject is dummy for refrence purpose only
console.log(type);
console.log(result);

here i can fetch my type array which i have declare perfectly but in 1st snippet i can't fetch result outside the map function

  • as i wrote my condition perfectly that's why its running perfectly inside map function but not outside the map function

Aucun commentaire:

Enregistrer un commentaire