简体   繁体   English

访问对象内的深层嵌套数组

[英]Getting access to deep nested arrays within objects

Here is an object with arrays that contain objects (similar to JSON you might get back from an API) 这是一个带有包含对象的数组的对象(类似于JSON,您可能会从API取回)

  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...',
        },
      ],
    },
  ],
};

To get access to the name of the business - it's business.name -> Google 要访问商家名称-商家名称-> Google

to get access to services array within bussiness I can do something like: 为了在业务范围内访问服务数组,我可以执行以下操作:

const services = business.services -> now I have my services array and can map over that: const services = business.services >现在,我有了我的服务数组,可以在上面映射:

services.map(service => {
 return services.name
}

I will get -> ['Google Voice', 'Google Maps'] 我会得到-> ['Google Voice','Google Maps']

But the services has it's own nested array (requests). 但是服务具有它自己的嵌套数组(请求)。 Now I can get access to that with: 现在,我可以通过以下方式访问它:

services.requests[0] or [1] services.requests [0]或[1]

The question is: How do I 'extract out' requests into it's own variable so that I may map over that as well without having to use [0][1] etc... 问题是:如何将请求“提取”到它自己的变量中,这样我也可以映射它而不必使用[0] [1]等...

If you want an array of arrays you can just map , if you want to flatten it use reduce : 如果需要数组数组,则可以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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM