简体   繁体   中英

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)

  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

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:

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

I will get -> ['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]

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...

If you want an array of arrays you can just map , if you want to flatten it use 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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