Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

223
Vistas
How can I sum total amount of properties in a nested object?

I did this code to sum the total amount of properties in a nested object but it doesn't works well, can you help me please ?

var obj = {
  a: {
    a1: 10,
    a2: 'Emily',
    a3: {E: 'm', i: 'l', y: {a: true}}
  },
  b: 2,
  c: [1, {a: 1}, 'Emily']
}

var i = 0
var countProps = function (obj) {
    
  for (const key in obj) {
    if ( obj[key].hasOwnProperty(key) )    
        i++;
      } 
    if ( typeof obj[key] === 'object' ) {
        i++;
        countProps( obj[key] );
      }
    }
      return i;
  };
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

See snippet. if ( obj[key].hasOwnProperty(key) ) is the part that's off, you're looking at the child and checking if it has the same key as well.

var obj = {
  a: {
    a1: 10,
    a2: 'Emily',
    a3: {E: 'm', i: 'l', y: {a: true}}
  },
  b: 2,
  c: [1, {a: 1}, 'Emily']
}

let i = 0;
var countProps = function (obj) {
  for (const key in obj) {
    if ( typeof obj[key] === 'object' ) {
        i++;
        countProps( obj[key] );
    } else {
      i++;
    } 
  }
  return i;
};
  
console.log(countProps(obj));

about 4 years ago · Juan Pablo Isaza Denunciar

0

I just solved this problem, here is the answer:)

var i = 0   
var countProps = function (obj) {
  for (const key in obj) {
    if ( obj[key] instanceof Object && !Array.isArray(obj[key]) ) {
        i++;
        countProps( obj[key] );
    } else {
      i++;
    } 
    }
  return i;
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda