Home > database >  How can I Neatly format a recursed console-logged Json Object in JavaScript?
How can I Neatly format a recursed console-logged Json Object in JavaScript?

Time:05-05

I recursively listed a nested json object. When i console log, I get my data in a way that makes it difficult to know where a set of object begins or ends.

How can I format the response?

const obj = {
      fullName: 'Ram Kumar',
      age: 31,
      gender: male
    }
  },
  fullName: 'Ranbir Singh',
    age: 22,
    gender: male
  }
},

function printAllVals(obj) {
  for (let prop in obj) {
    if (typeof obj[prop] === "object") {
      printAllVals(obj[prop])
    } else {
      console.log(prop   ':'   obj[prop]);
    }
  }
}

I am getting:

fullName:Ram Kumar
age: 31
gender: male
fullName:Ranbir Singh
age: 22
gender: male

What I want is something like this. Anything to format or separate the objects for clarity or easy understanding :

fullName:Ram Kumar
age: 31
gender: male 
---
fullName:Ranbir Singh
age: 22
gender: male

CodePudding user response:

Your object does not look valid, so I added a "child" sub-key to iterate down into.

Before you call the recursive function call, print a line-separator.

const printAllVals = (obj) => {
  for (let prop in obj) {
    if (typeof obj[prop] === 'object') {
      console.log('---');                  // Print line, before the child.
      printAllVals(obj[prop])
    } else {
      console.log(`${prop}: ${obj[prop]}`);
    }
  }
}

const obj = {
  fullName: 'Ram Kumar',
  age: 31,
  gender: 'male',
  child: {                                // sub-key?
    fullName: 'Ranbir Singh',
    age: 22,
    gender: 'male'
  }
};

printAllVals(obj);
.as-console-wrapper { top: 0; max-height: 100% !important; }

  • Related