简体   繁体   中英

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

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

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

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