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;
});
};
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
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
Top comments (0)