How to convert a list of objects with each object having an array of elements, to an array of objects with the subelement as a property How to convert a list of objects with each object having an array of elements, to an array of objects with the subelement as a property mongoose mongoose

How to convert a list of objects with each object having an array of elements, to an array of objects with the subelement as a property


Instead of first fetching the data from the database in the format you don't want and then converting it to a format you want, you could use aggregation to get the data from MongoDB in the desired format:

db.collection.aggregate([  { $unwind: "$blogs" },  {    $project: {      "_id": 0,      name: 1,      blogs: 1,      date: {        $dateFromString: {          dateString: "$blogs.created"        }      }    }  },  { $sort: { date: -1 } },  { $project: { date: 0 } }])

Explanation of aggregation pipeline stages used in above query:

  1. $unwind - deconstruct blogs array to output a separate document with each object in the blogs array

  2. $project - hide _id field, show name and blogs field and create a new field named date and set its value equal to the field created converted to date. (The value of the created field is converted to a date to sort the documents correctly based on the date instead of the date string.)

  3. $sort - sort the documents based on date field in descending order (-1 for descending, 1 for ascending), i.e. from the most recent date to older date.

  4. $project - hide the date field from the output documents

For details on the above mentioned aggregation pipeline stages, see:

Demo:

This demo shows the above mentioned query in action.


Try with Array.prototype.reduce. Something like this -

const data = [    {        "name": "user1",        "blogs": [            {                "title": "blog1",                "created": "01-01-2020"            },            {                "title": "blog2",                "created": "01-01-2020"            }        ]    },    {        "name": "user2",        "blogs": [            {                "title": "blog3",                "created": "01-01-2020"            },            {                "title": "blog4",                "created": "01-01-2020"            }        ]    }];const result = data.reduce((acc, curr) => {    const { name, blogs } = curr;    const blogArr = blogs.map((blog) => {        return {            name,            blog        };    });    Array.prototype.push.apply(acc, blogArr);    return acc;}, []);console.log(result);