0

Let's say I have an array like so...

const myCustomers = [
    {
        accounts: [
            {
                accountID: 1234
            },
            {
                acountID: 2345
            }
        ]
    },
    {
        accounts: [
            {
                accountID: 3456
            }
        ]
    },
    {
        accounts: [
            {
                accountID: 4567
            },
            {
                accountID: 5678
            }
        ]
    }
];

I'm basically just trying to create an array of all the accountIDs, so it looks something like this...

const accountIDs = [1234, 2345, 3456, 4567, 5678];

I've tried using map but I'm not having luck.

const myRes = myCustomers.map(a => a.accounts.accountID);

1 Answer 1

4

You can do this using map() & flat():

myCustomers.map(c => c.accounts).flat().map(c => c.accountID)

DEMO:

const myCustomers=[{accounts:[{accountID:1234},{accountID:2345}]},{accounts:[{accountID:3456}]},{accounts:[{accountID:4567},{accountID:5678}]}];  
const result = myCustomers.map(c => c.accounts).flat().map(c => c.accountID);
console.log( result )

Or, a better approach using flatMap():

myCustomers.flatMap(c => c.accounts).map(c => c.accountID)

The flatMap() method basically first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map() followed by a flat(), but flatMap() is often quite useful, as merging both into one method is slightly more efficient.

DEMO:

const myCustomers=[{accounts:[{accountID:1234},{accountID:2345}]},{accounts:[{accountID:3456}]},{accounts:[{accountID:4567},{accountID:5678}]}];  
const result = myCustomers.flatMap(c => c.accounts).map(c => c.accountID);
console.log( result )

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks... this did exactly what I needed.

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.