1

I have an array of objects, and each objects may contain another array of objects, I want to concatenate values of nested array and generate a new array.

For example

lessons = [
 {
   id: 1,
   description: string,
   material: [{obj1}, {obj2}]
 },
 {
   id: 2,
   description: string,
   material: [{obj3}]
 },
 {
   id: 3,
   description: string,
   material: [{obj4}, {obj5}, {obj6}]
 }
]

I want to generate a new array only contains material, expected output would like this

materials = [
   {obj1},
   {obj2},
   {obj3},
   {obj4},
   {obj5},
   {obj6}
 ]

how can I do that by using lodash?

1 Answer 1

2

You can use .flatMap to iterate over lessons, and return all the material lists in one array:

const lessons = [
 { id: 1, description: 'string', material: [{obj1:1}, {obj2:2}] },
 { id: 2, description: 'string', material: [{obj3:3}] },
 { id: 3, description: 'string', material: [{obj4:4}, {obj5:5}, {obj6:6}] }
];

const res = _.flatMap(lessons, ({ material = [] }) => material);

console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous"></script>

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

4 Comments

I can't run the code snippet, it shows _ is not defined. I can see the usage is from lodash doc, can I just write it like : const res = flatMap(lessons, e => e.material || []) without underscore?
@RH-st you stated that you need to use lodash so make sure to have it installed. If you want to use it normally, try this: lessons.flatMap(({ material = [] }) => material);
Amazing! That really help!! Thanks a lot, can I ask for deeper explanation? so lessons.flatMap() means lessons is already become the first argument which is the collection, therefore we only need to pass the second argument which is ({ material = [] }) => material be the iteratee function, right?
@RH-st you're welcome. Basically, it's a function in Array.prototype and the argument is the callback function that gets executed in each iteration. This is the reference for the docs: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

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.