You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript数组中过滤null/undefined值?处理map场景空值问题

How to Filter Null/Undefined Values When Accessing Nested Object Properties

Got it, this is a super common pain point when working with arrays and nested objects in JavaScript! Let’s walk through a few clean, reliable ways to fix that error and get only valid description values.

Method 1: Filter First, Then Map (Most Efficient)

This approach is my go-to because it eliminates invalid entries before we even start mapping, which saves unnecessary processing—especially if your dataSku array is large.

const values = dataSku
  // Filter out any sku where map.skuInfo[sku] is null or undefined
  .filter(sku => map.skuInfo[sku] != null)
  // Now we safely access description since we know skuInfo exists
  .map(sku => map.skuInfo[sku].description);

The != null check is a neat shorthand that catches both null and undefined in one go—way cleaner than writing map.skuInfo[sku] !== null && map.skuInfo[sku] !== undefined.

Method 2: Map with Optional Chaining, Then Filter Results

If you prefer to map first (maybe you need to keep the array length consistent temporarily), you can use the optional chain operator (?.) to avoid errors, then filter out any invalid results:

const values = dataSku
  // Optional chain returns undefined if skuInfo is null/undefined
  .map(sku => map.skuInfo[sku]?.description)
  // Remove any undefined or null entries from the final array
  .filter(desc => desc != null);

The ?. operator stops the property access as soon as it hits a null/undefined value, so it won’t throw that dreaded "Cannot read property" error.

Bonus: Keep Placeholder Values Instead of Filtering

If you don’t want to remove entries but instead replace invalid ones with a placeholder (like an empty string), use the nullish coalescing operator (??) alongside optional chaining:

const values = dataSku.map(sku => map.skuInfo[sku]?.description ?? '');

This will give you an array where invalid entries are replaced with '' instead of being removed—perfect if you need to maintain the original array length.


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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:54:06