0

What is a fast way of mapping data like the data below using lodash into a single array of level2 objects.

    SomeObject = {
    name: 'someObject',
    level1: [
        {
            id: '1',
            level2: [
                { someValue: 'example1'},
                { someValue: 'example2'},
                { someValue: 'example3'},
                { someValue: 'example4'}
            ]
        },
        {
            id: '2',
            level2: [
                { someValue: 'example5' },
                { someValue: 'example6' },
                { someValue: 'example7' },
                { someValue: 'example8' }
            ]
        },
        {
            id: 'n',
            level2: [
                { someValue: 'examplen' },
            ]
        }
    ]
}

output:

[
 'example1',
 'example2',
 'example3',
 'example4',
 'example5',
 'example6',
 'example7',
 'example8',
 'examplen',
]

ignore: Stackflow is smarter than I so I have to type more non code stuff for it to stop complaining. So I'll type more so that I may post.

1 Answer 1

3

You can use flatMap() to collect all the "level2" arrays into a single array and then extract the "someValue" properties with a simple map()

_.map(_.flatMap(SomeObject.level1, "level2"),"someValue")
Sign up to request clarification or add additional context in comments.

4 Comments

My output was wrong and its been edited to the correct output. Sorry for the confusion! ugh its supposed to be an array of strings.
Then just add another map() to extract the someValue property.
That'll create an array of arrays and then flatten handles it. Genius. Thank you
@Calvin Now that i'm back at my computer, i've updated the answer to use flatMap. That basically does both the map and flatten

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.