0

I have some data that is an array of objects like so:


let employees = 
[
    {
        emp_id: "1",
        course_data : [
            {
                info: "info",
                for: "emp_id_1"
            },
            {
                info: "more_info",
                for: "emp_id_1 "
            },
            {
                info: "even_more_info",
                for: "emp_id_1 "
            },

        ],

        emp_id: "2",
        course_data : [
            {
                info: "info",
                for: "emp_id_2"
            },
            {
                info: "more_info",
                for: "emp_id_2 "
            },
            {
                info: "even_more_info",
                for: "emp_id_2 "
            },

        ],
    },
];

I want to create a conatenated array of objects from the course_data property all objects in the parent array have. In other words, I'd like to have my data in the following format so that I can run _.groupBy() on the it:

let concatenated_array = [
            {
                info: "info",
                for: "emp_id_1"
            },
            {
                info: "more_info",
                for: "emp_id_1 "
            },
            {
                info: "even_more_info",
                for: "emp_id_1 "
            },

            {
                info: "info",
                for: "emp_id_2"
            },
            {
                info: "more_info",
                for: "emp_id_2 "
            },
            {
                info: "even_more_info",
                for: "emp_id_2 "
            },

        ]

I'm thinking something like unionWith, but I'm not sure. Is this possible in lodash?

2
  • Your original data is invalid in its present form, since it has multiple properties with the same key (multiple emp_ids, for instance). Assuming that's a typo, and you actually have an array of individual objects, there are a few duplicates on Stack Overflow. What research have you done and attempts made based on that research? Commented Jun 29, 2022 at 20:41
  • But with lodash you're looking for _.flatMap (_.flatMap(employees, 'course_data')) Commented Jun 29, 2022 at 22:20

1 Answer 1

1

You can do it with only javascript tools, like that:

employees.map(empl => empl.course_data).flat()
Sign up to request clarification or add additional context in comments.

1 Comment

Or just use Array.prototype.flatMap which is slightly more efficient than calling both methods separately.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.