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

Author: BgRnD Official

Official representative of BgRnd Team on this website

Leave a Reply