0

I have one array with two objects in them. I used a Promise All to get both of these. I'm having a hard time trying to merge them because I need it to be dynamic. I have been messing around with a bunch of array functions like map, forEach, etc etc but I can't seem to find any that work properly.

So I've tried the map function so many times. The thing is, it keeps getting assigned to a new array, which isn't good. I need it to be an object. If I can merge a dynamic amount of objects within the array, then I can easily convert it to an object but that's also been an issue.

this is the promise all

        let response = await Promise.all(
            key.map(async tag => {
                let params = { params: { tag: tag } };
                let promise = await axios.get(url, params);
                return promise.data;
            })
        );

My sad attempt at giving it a go :(

        let merged = response.map(x => {
            let obj = { ...x };
            return obj;
        });

I've shortened a lot of the JSON but this is the gist of it.

[
    {
        "posts": [
            {
                "author": "Zackery Turner",
                "authorId": 12,
                "id": 2,
                "tags": [
                    "startups",
                    "tech",
                    "history"
                ]
            }
        ]
    },
    {
        "posts": [
            {
                "author": "Rylee Paul",
                "authorId": 9,
                "id": 1,
                "tags": [
                    "tech",
                    "health"
                ]
            }
        ]
    }
]

I'm honestly just completely stumped. I don't know what I can do that will give me a dynamic solution.

Ideally, it would come out like this:

{
        "posts": [
            {
                "author": "Zackery Turner",
                "authorId": 12,
                "id": 2,
                "tags": [
                    "startups",
                    "tech",
                    "history"
                ]
            },
            {
                "author": "Rylee Paul",
                "authorId": 9,
                "id": 1,
                "tags": [
                    "tech",
                    "health"
                ]
            }

Also, please I understand that I'm trying to do this dynamically. I wish it were as easy as hard coding it, but that's the solution that I see comes up when I browse similar threads on StackOverflow.

1 Answer 1

2

You could use flatMap to get a flattened array of posts. Then use Shorthand property names to create an object with a posts property

const array = [{posts:[{author:"Zackery Turner",authorId:12,id:2,tags:["startups","tech","history"]}]},{posts:[{author:"Rylee Paul",authorId:9,id:1,tags:["tech","health"]}]}],
      posts = array.flatMap(a => a.posts),
      output = { posts };
      
console.log(output)

If flatMap is not supported, use concat to merge the individual posts array like this:

const array = [{posts:[{author:"Zackery Turner",authorId:12,id:2,tags:["startups","tech","history"]}]},{posts:[{author:"Rylee Paul",authorId:9,id:1,tags:["tech","health"]}]}],
      posts = [].concat(...array.map(a => a.posts)),
      output = { posts };

console.log(output)

Or use a simple for...of loop and push every posts to an array

const array = [{posts:[{author:"Zackery Turner",authorId:12,id:2,tags:["startups","tech","history"]}]},{posts:[{author:"Rylee Paul",authorId:9,id:1,tags:["tech","health"]}]}],
    posts = [];

for (const o of array)
  posts.push(...o.posts);

console.log({ posts })

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

6 Comments

Hey thank you so much! I didn't think to use the concat method for some reason... Is there a reason you restructure post ?
@DanielLee I didn't restrcuture any posts. Which are you referring to?
Sorry I meant destructure. Sorry about that. Been using Safari and it has this habit of auto correcting my spelling.
@DanielLee that's not destructuring. That's Shorthand property names. So, if you have a variable which is same as the property you want to add, you can skip the :. For example If you have var name = "Lee", age = 20 and you want to create this object -> { name: "Lee", age: 20 }, you would normally do { name: name, age: age }. You can skip that and use { name, age }. So, in the snippet it ends up being const output = { posts: posts }.
Ohhh. I understand. Thank you so much for the help! I've noticed that with the concat method, the second array starts exactly where it was, whereas the API that I'm connecting is supposed to order it by certain parameters. Does the concat method block that from happening?
|

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.