如何提取对象中嵌套的requests数组并实现无索引遍历?
提取所有嵌套的requests为独立数组的方法
嘿,这事儿其实挺容易解决的!我们可以利用JavaScript数组的内置方法,把所有service里的requests数组合并成一个单独的一维数组,这样你就能直接遍历它,完全不用靠索引来访问啦。
方法一:使用flatMap(推荐)
flatMap是专门用来处理这种“映射+扁平化”场景的方法,它会先遍历每个service,取出对应的requests数组,然后自动把这些数组合并成一个一维数组:
const business = { name: 'Google', location: 'Venice, Ca', services: [ { name: 'Google Voice', requests: [ { summary: 'Read my lips', details: 'Details of of the request...', }, { summary: 'Log in with face recoginition', details: 'Details of of the request...', }, ], }, { name: 'Google Maps', requests: [ { summary: 'Make it rain', details: 'Details of of the request...', }, { summary: 'Make it shine', details: 'Details of of the request...', }, ], }, ], }; // 提取所有requests到独立数组 const allRequests = business.services.flatMap(service => service.requests); // 现在可以直接遍历啦,不用索引! allRequests.forEach(request => { console.log(`请求摘要:${request.summary}`); });
运行这段代码后,allRequests就是包含所有4个请求对象的一维数组,你可以用任何数组方法(比如map、filter、forEach)来操作它,完全不用关心原来的嵌套结构。
方法二:map + flat(兼容旧环境)
如果你的运行环境不支持flatMap(比如一些非常老的浏览器),可以先用map把每个service的requests取出来得到一个二维数组,再用flat()把它扁平化:
const allRequests = business.services.map(service => service.requests).flat();
这个方法和flatMap的效果完全一样,只是分两步完成而已。
效果验证
现在你可以直接打印allRequests看看结果:
console.log(allRequests); // 输出: // [ // { summary: 'Read my lips', details: 'Details of of the request...' }, // { summary: 'Log in with face recoginition', details: 'Details of of the request...' }, // { summary: 'Make it rain', details: 'Details of of the request...' }, // { summary: 'Make it shine', details: 'Details of of the request...' } // ]
这样不管有多少个service,每个service里有多少个requests,都能一次性提取出来,轻松遍历~
内容的提问来源于stack exchange,提问作者SakoBu
相关产品推荐
相关产品推荐

