How to count the true of an array of objects

0

I have a json and I need to be able to count how many true there is, since it says if a patient is interned or not.

{
    "pacientes" : [
        {
            "nroPaciente":  2,
            "nombre": "Anakin Skywalker",
            "edad": 50,
            "internado": true
        },
        {
            "nroPaciente":  1,
            "nombre": "Emanuel Fernandez",
            "edad": 16,
            "internado": false
        },
        {
            "nroPaciente":  3,
            "nombre": "Julieta Otoño",
            "edad": 32,
            "internado": false
        }
]
}

I got here by showing it by console, but I need to paint it on the screen in a number and not with Boolean values

function cantidadInter(){
    fetch('./pacientes.json')
        .then(res => res.json())
        .then(data => {

            let filtro= data.pacientes.filter(elemento => elemento.internado === true);
            //console.log(filtro);

               // console.log(filtro);
                for(let i of filtro){
                    console.log(i.internado);    
                }
        });   
} 
    
asked by lucas 12.09.2018 в 01:20
source

3 answers

2

I try this:

for(var i = 0; i < filtro.length; i++){
    //crear elemento
    var label = document.createElement('label');
    //asignar texto o cualquier key que ocupes
    label.innerHTML = filtro[i].nroPaciente;
    //agregar a tu div o donde lo ocupes
    tuDiv.appendChild(label);
    //y asi consecutivamente con los elementos que ocupes crear y mostrar en tu div
}
    
answered by 12.09.2018 / 01:49
source
1
var total = data.pacientes.reduce(function(total, current) {

  if (current.internado) {
    total += 1;
  }
  return total;
}, 0);
// total contiene el numero de pacientes que tienen true
var p = document.createElement('p');
p.innerText = total;
elementoAInsertar.appendChild(p);
    
answered by 12.09.2018 в 07:20
1

I think you are using EcmaScript6, so we could leave it even shorter, using arrow and destructuring functions, and in turn implementing a ternary conditional.

function cantidadInter(){
  fetch('./pacientes.json')
    .then(res => res.json())
    .then(({ pacientes }) => {

        const longitud = pacientes.reduce((acc, { internado }) => internado ? acc ++ : acc, 0);
        console.log(longitud);
    });
    
answered by 13.09.2018 в 00:59