0

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

1
  • Can use any array method on that nested array. What exactly are you wanting to do with them? Commented Dec 31, 2017 at 19:14

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.