You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

遍历对象时遇报错:无法将undefined或null转换为对象

Hey, let's break down and fix your issue step by step!

First, let's understand the two problems in your code

1. Logical error in the map function

Object.keys(items) returns an array of the object's key names, not the values. For your items object, this array would be ["id", "name", "currency"]. When you use index.name in the map callback, you're trying to access a name property on a string (like "id"), which doesn't exist. That's not what you want here.

2. The "cannot convert undefined or null to object" error

This happens because Object.keys() requires a valid object as input. If your items variable ever becomes null or undefined when this code runs, calling Object.keys(items) will throw this exact error.

Fixes to resolve both issues

Option 1: Get all property values correctly

If your goal is to extract all values from the items object, use either of these approaches:

Using Object.values() (simplest way)

const result = Object.values(items);
console.log(result); // Output: [1, "name1", "usd"]

Using Object.keys() with proper value access

If you need to work with the key names while getting values:

const result = Object.keys(items).map(key => items[key]);
console.log(result); // Output: [1, "name1", "usd"]

Option 2: Prevent null/undefined errors

To avoid the conversion error entirely, add a check to ensure items is a valid object before processing it:

// Safely handle cases where items might be null/undefined
const safeItems = items ?? {}; // Fallback to empty object if items is null/undefined
const result = Object.keys(safeItems).map(key => safeItems[key]);
console.log(result);

Or with a type check for extra safety:

const result = typeof items === 'object' && items !== null
  ? Object.keys(items).map(key => items[key])
  : []; // Return empty array if items is invalid
console.log(result);

Bonus: Iterate over key-value pairs

If you need both keys and values, use Object.entries():

const result = Object.entries(items).map(([key, value]) => ({ key, value }));
console.log(result);
// Output: [{key: "id", value: 1}, {key: "name", value: "name1"}, {key: "currency", value: "usd"}]

内容的提问来源于stack exchange,提问作者saon

火山引擎 最新活动