简体   繁体   中英

get element index of an object

i need to get the index of an element in this object (returned as JSON.parse(data) ), i tried with findIndex datosReserva , datosReserva.Reservas and nothing... it says findIndex is not a function.

function checkReserva(){
 
  var options = {
    'method': 'GET',
    'uri': urlAPI,
    'headers': {
      'Content-Type': 'application/x-www-form-urlencoded',
    
    }
  };
request(options, function (error, response) {
  let reserva;
  if (error){ 
    throw new Error(error);
  }else {
   // console.log(response.body);
    reserva = response.body;
    //console.log(reserva)

  }
return checkIndex(reserva, "2929 25-06-2020 10:00");
//"2929 25-06-2020 10:00" for testing
});

}
function checkIndex(datosReserva, reserva) {
    const elemento = (element) => element.reserva == reserva;
    console.log(datosReserva.findIndex(elemento))
}
{
  "Reservas": [
    {
      "reserva": "2929 22-06-2020 11:20",
      "id": "1",
      "status": "on"
    },
    {
      "reserva": "2929 25-06-2020 10:00",
      "id": "5",
      "status": "on"
    }
  ]
}
var Reservas = Json.parse(response.body).Reservas;
return checkIndex(Reservas , "2929 25-06-2020 10:00");
function checkIndex(Reservas, reserva) {
    let index = -1;
    Reservas.forEach((element, idx)=>{
         if(element.reserva == reserva) {
            index = idx;
         }
    });
    return index;
}

well i found the solution. I needed to parse the response to object. Thank you everyone!!

function checkIndex(datosReserva, stringReserva){
  var reservas = JSON.parse(datosReserva)
  const elemento= (element) => element.reserva == stringReserva;
var index = reservas.Reservas.findIndex(elemento);
  console.log(reservas.Reservas.findIndex(elemento));
 //return index;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM