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

如何优化将数组/对象类型的content.categories转为id数组的代码?

优化方案

可以用更简洁的方式统一处理两种情况,省去条件判断逻辑:

const categoriesIds = [].concat(content.categories).map(category => category.id);

逻辑说明

  • [].concat() 会自动适配参数类型:如果传入的是数组,直接返回该数组的副本;如果是单个对象,会自动将其包装成数组。
  • 一行代码完成「统一格式+提取id」的操作,比原代码更简洁直观。

边界情况适配

如果 content.categories 可能为 null 或 undefined,可以加上空值处理避免报错:

// 处理null/undefined的场景
const categoriesIds = [].concat(content.categories ?? []).map(category => category.id);

也可以用 flat() 方法实现类似效果:

const categoriesIds = [content.categories].flat().map(category => category.id);
// 若需过滤null/undefined,再加filter
const categoriesIds = [content.categories].flat().filter(Boolean).map(category => category.id);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 23:32:32