Home > OS >  How can I sum total amount of properties in a nested object?
How can I sum total amount of properties in a nested object?

Time:03-30

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;
  };

CodePudding user response:

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));

CodePudding user response:

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;
};
  • Related