DEV Community

HarmonyOS
HarmonyOS

Posted on

How can I correctly print object information in logs when console.log shows only [object Object]?

Read the original article:How can I correctly print object information in logs when console.log shows only [object Object]?

Question

How can I correctly print object information in logs when console.log shows only [object Object]?

Short Answer

[object Object] appears because string interpolation implicitly calls Object.prototype.toString(). To see the object’s contents, either (1) serialize it with JSON.stringify, or (2) cast it to the right type and log specific fields. Also watch out for non-serializable values (functions, symbols) and circular references when using JSON.stringify.

Example 1: Use JSON.stringify()

  let obj: Record<string, Object> = { name: 'abc', id: 123 };
  let param: HashMap<string, Object> = new HashMap<string, Object>();
  param.set('obj', obj);

  console.log(`param info (raw): ${param.get("obj")}`);                  // → [object Object]
  console.log(`param info (json): ${JSON.stringify(param.get("obj"))}`); // → {"name":"abc","id":123}
  Tips: If there may be circular references, use a replacer:
  const safeStringify = (v: unknown) => {
    const seen = new WeakSet();
    return JSON.stringify(v, (k, val) => {
      if (typeof val === 'object' && val !== null) {
        if (seen.has(val)) return '[Circular]';
        seen.add(val);
      }
      return val;
    });
  };
Enter fullscreen mode Exit fullscreen mode

Example 2: Cast to the proper type and log fields

  let obj: Record<string, Object> = { name: 'abc', id: 123 };
  let param: HashMap<string, Object> = new HashMap<string, Object>();
  param.set('obj', obj);

  const val = param.get('obj') as Record<string, Object>;
  console.log(`param name: ${val['name']}, id: ${val['id']}, typeof: ${typeof val}`);
  // → param name: abc, id: 123, typeof: object
Enter fullscreen mode Exit fullscreen mode

Applicable Scenarios

· ArkTS / JavaScript logging where template strings include objects

· Debugging data structures (e.g., values pulled from FormData, maps, or APIs)

· Printing selective fields for readable logs in production

Written by Zulfu Balkan

Top comments (0)