Print all properties of JavaScript object

Printing out variables using console.log(variable) is a common way to debug Web Applications. But for object variables looking thru a tree of properties, prototype, and so on is quite annoying…

Here is a simple React Component for outputting a JavaScript object as a HTML <ul> list. Internal properties of object type are also printed as sublists:

export const ListObjectProps = (props) => {
  const { object } = props;

  function renderObjectProps() {
    const result = [];
    for (const property in object) {
      if (typeof object[property] === 'object') {
        result.push(
          <li key={property}>
            {property}:
            <ListObjectProps object={object[property]} />
          </li>
        );
      } else {
        result.push(<li key={property}>{`${property}: ${object[property]}`}</li>);
      }
    }
    return result;
  }

  return <ul>{renderObjectProps()}</ul>;
};

To print the object properties use following JSX code:

  <ListObjectProps object={anyJavaScriptObject} />

Destructuring and access “props” in the same time

Modern ES6 syntax of destructuring becomes popular between JavaScript developers:

const { a, b = defaultValue, c } = props;

React developers also start using this technique, especially for functional components:

const component = ({ index, data = 0, onClick }) => {
...
}

But a new problem (beside unreadable code…) appears:

How to access props.children and other sub-properties that were not extracted?

The solution is simple, use …spread JavaScript syntax!

const component = ({ index, data = 0, onClick, ...props }) => {
...
  <li key={index} onClick={onClick.bind(data)}>
    {props.children}
  </li>
...
}

This is the shortest single line solutions to unpack properties and access the rest of object’s data at the same time!

Anyway, you can always roll back to readable JS code, just add a single line:

const component = (props) => {
  const { index, data = 0, onClick } = props; 
...
  <li key={index} onClick={() => onClick(data)}>
    {props.children}
  </li>
...
}