'How to deconstruct an object using JavaScript?

So I tried to fetch data from my API, and I used concat and promise.all, here's my code

public async timelinePost(user_id:string){
        const currentUser:any = await LocalAuthModel.findById(user_id)
        const userPosts = await PostModel.find({userId:user_id});
        const friendPosts = await Promise.all(
            currentUser.followings.map((friendId:any)=>{
                return PostModel.find({userId:friendId})
            })
        )
        console.log(userPosts)
        console.log(friendPosts)
        const posts = (userPosts as unknown[]).concat(friendPosts)
        return posts;
    }

I have to use map to find all the followings's post of current user , so I used map, and here's friendPosts look like.

[
  [
    {
      likes: [],
      _id: 60f012d6aa101557b2c3ff82,
      userId: '60ebc2584a6ed456750998b4',
    },
    {
      likes: [],
      _id: 60f012f0aa101557b2c3ff8c,
      userId: '60ebc2584a6ed456750998b4',
    }
  ]
]

and when I tried to combine these two it looks like below

[
        {
            "likes": [],
            "_id": "60ecd2521599b86baeb89b98",
            "userId": "60ebc2404a6ed456750998b1",
        },
        {
            "likes": [],
            "_id": "60ef06eeff7b684c1e6803c5",
            "userId": "60ebc2404a6ed456750998b1",
        },
        [
            {
                "likes": [],
                "_id": "60f012d6aa101557b2c3ff82",
                "userId": "60ebc2584a6ed456750998b4",
            },
            {
                "likes": [],
                "_id": "60f012f0aa101557b2c3ff8c",
                "userId": "60ebc2584a6ed456750998b4",
            }
        ]
]

I wonder how to remove the [] in friendPosts because apparently that's not what it supposed to be.



Solution 1:[1]

You can use Array.flat()

const users = [
        {
            "likes": [],
            "_id": "60ecd2521599b86baeb89b98",
            "userId": "60ebc2404a6ed456750998b1",
        },
        {
            "likes": [],
            "_id": "60ef06eeff7b684c1e6803c5",
            "userId": "60ebc2404a6ed456750998b1",
        },
        [
            {
                "likes": [],
                "_id": "60f012d6aa101557b2c3ff82",
                "userId": "60ebc2584a6ed456750998b4",
            },
            {
                "likes": [],
                "_id": "60f012f0aa101557b2c3ff8c",
                "userId": "60ebc2584a6ed456750998b4",
            }
        ]
]

console.log(users.flat())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nikola Pavicevic