这是一个包含对象的数组的对象(类似于您可能从API获取的JSON)
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...',
},
],
},
],
};
要访问商家名称 - 它是business.name - >谷歌
在商务中访问服务数组我可以做类似的事情:
const services = business.services
- >现在我有我的服务数组,可以映射:
services.map(service => {
return services.name
}
我会得到 - > ['Google Voice','Google Maps']
但是服务有它自己的嵌套数组(请求)。现在我可以通过以下方式访问:
services.requests [0]或[1]
问题是:我如何'将'请求提取到它自己的变量中,这样我就可以映射它而不必使用[0] [1]等......
答案 0 :(得分:1)
如果你想要一个数组数组,你可以map
,如果你想要展平它,请使用reduce
:
const reqs = business.services.map(service => service.requests);
console.log(reqs);
const flat = business.services.reduce((acc, service) => [...acc, ...service.requests], []);
console.log(flat);