如何在JavaScript中从嵌套数组结构提取所有id值
提取嵌套数组中所有id值的几种JavaScript方法
针对你给出的嵌套数据结构,这里有几种实用的方法提取所有id值:
1. 简洁的现代写法(flatMap + map)
利用ES6的flatMap先展开第一层嵌套数组,再用map提取id:
const allIds = test.flatMap(obj => obj.items.map(item => item.id));
2. 灵活的累加式写法(reduce)
如果需要在收集过程中做额外处理,reduce是更灵活的选择:
const allIds = test.reduce((result, current) => { // 把当前对象items里的所有id添加到结果数组 result.push(...current.items.map(item => item.id)); return result; }, []);
3. 易读的传统循环写法(forEach)
适合刚接触JS的开发者,逻辑直观清晰:
const allIds = []; // 遍历外层数组的每个对象 test.forEach(obj => { // 遍历当前对象的items数组 obj.items.forEach(item => { allIds.push(item.id); }); });
额外处理:过滤无id的项
如果存在item没有id属性的情况,可以添加过滤逻辑:
const allIds = test.flatMap(obj => obj.items.map(item => item.id).filter(id => typeof id !== 'undefined') );
内容的提问来源于stack exchange,提问作者Rupak
相关产品推荐
相关产品推荐

