Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

220
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!