如何用单循环更简洁提取嵌套对象数组中的所有ID?
提取嵌套对象数组中的所有ID
我有如下结构的对象数组,需要提取其中所有ID:
const arr = [ { "id": "1", }, { "id": "2", "options": [ { "id": "2.1", } ] }, ]
我目前通过以下代码实现了需求:
const one = arr.map(ob => ob.id) const two = arr.flatMap(ob => ob.options).map(ob => ob?.id).filter(Boolean) console.log([...one, ...two])
该代码输出结果为['1', '2', '2.1'],符合预期,但有没有更简洁或更简短的实现方式?
简洁实现方案
方案一:单遍flatMap合并处理
用flatMap一次性将每个对象的自身ID和options中的ID整合,同时通过可选链和空数组兜底避免报错:
const allIds = arr.flatMap(obj => [ obj.id, ...(obj.options?.map(opt => opt.id) || []) ]) console.log(allIds) // ['1', '2', '2.1']
方案二:递归处理(兼容深层嵌套)
如果后续可能出现更深层级的嵌套结构,递归方案的扩展性更强:
function extractIds(items) { return items.flatMap(item => [ item.id, ...(item.options ? extractIds(item.options) : []) ]) } const allIds = extractIds(arr) console.log(allIds) // ['1', '2', '2.1']
方案三:reduce累积收集
用reduce遍历一次数组完成所有ID的累积,逻辑直观清晰:
const allIds = arr.reduce((acc, obj) => { acc.push(obj.id) obj.options?.forEach(opt => acc.push(opt.id)) return acc }, []) console.log(allIds) // ['1', '2', '2.1']
内容的提问来源于stack exchange,提问作者Florence
相关产品推荐
相关产品推荐

