Ways to dynamically combine a group of objects

I'm grappling with a challenge involving an array containing two objects. After using Promise All to fetch both of these objects, I've hit a roadblock in trying to merge them dynamically. Despite experimenting with various array methods like map, forEach, and others, I have yet to find one that fits my requirements.

My attempts with the map function have fallen short numerous times. Each time, it results in being assigned to a new array, not serving my purpose of needing it as an object. My goal is to merge a fluctuating number of objects within the array seamlessly, but so far, this task has proven tricky.

This snippet showcases my use of 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;
            })
        );

Below lies my unsuccessful endeavor at solving the problem:

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

The JSON data presented here has been condensed for clarity purposes.

[
    {
        "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 feeling stuck and unsure about finding a dynamic solution to this problem.

Essentially, I'm aiming for an output in this format:

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

I acknowledge the complexity of seeking a dynamic solution rather than resorting to hard coding, which appears to be the common advice found on similar discussions on platforms like StackOverflow.

Answer №1

You can utilize the flatMap method to obtain a flattened array of posts. Then, leverage Shorthand property names to construct 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 your environment does not support flatMap, you can combine individual posts arrays using concat as demonstrated below:

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)

Alternatively, you can employ a straightforward for...of loop and use push to add every posts item 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 })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The byte order of integer literals in JavaScript

When writing the following line in Javascript: var n = 0x1234, is it always true that n == 4660? This question could also be phrased as follows: Does 0x1234 represent a series of bytes with 0x12 as the first byte and 0x34 as the last byte? Or does 0x1234 r ...

Slick Slider fails to load on web browsers

Hi everyone, I have a snippet of HTML code that I need help with: <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css"/> </head> <body> ...

Error message: The function send() cannot be applied to the object received by request.post() in Node

As I embark on testing the functionalities of my node.js website using chai and mocha, I encountered an issue when running npm test. The error message displayed is: ' TypeError: request.post(...).send is not a function' Referencing the code sni ...

What is the best way to transfer a variable from jQuery to a PHP script?

While I am aware that similar questions have been asked in the past, I am facing a unique challenge in trying to create a table with distinct links and pass the id of the link to a PHP page. Here is what I have so far: echo("<p>To reser ...

What could be the reason behind the malfunctioning of a custom filter in this specific Vue 3 application?

In my development project, I am creating a Vue 3 CRUD application for managing Users. The goal is to display the users in reverse order so that the newest additions appear at the top. To achieve this, I have implemented a custom filter as shown below: reve ...

This TypeScript error occurs when trying to assign a value of type 'null' to a parameter that expects a type of 'Error | PromiseLike<Error | undefined> | undefined'

Currently, I am making use of the Mobx Persist Store plugin which allows me to store MobX Store data locally. Although the documentation does not provide a TypeScript version, I made modifications to 2 lines of code (one in the readStore function and anot ...

the countdown function could not access the inst variable

I found an amazing plugin at that I'm using. Currently, I have 3 countdown timers that are loaded with a json array. However, when I try to recharge them, they become blocked and the following error message pops up: TypeError: inst.options is undef ...

AngularJS: Click on image to update modelUpdate the model by clicking

I am a newcomer to AngularJS and I am attempting to update my model after the user clicks on an image. Below is the code for this: <div class="col-xs-4 text-center"><a ng-model="user.platform" value="ios"><img src="ios.png" class="img-circl ...

Next.js version 14 is having difficulties displaying the loading.tsx file

click here for image description Why is the loading not displaying when navigating to /profile? How can I fix this issue? export default function Loading() { // You can add any UI inside Loading, including a Skeleton. return ( <div> lo ...

Differences between jQuery and Google Closure in terms of handling AJAX

Recently, I've been exploring the Google Closure Library for handling ajax calls. I came across an example that piqued my interest: goog.events.listen(request, "complete", function(){ if (request.isSuccess()) { // perform a cool action } els ...

The Handlebar helper functions in SailsJs seem to be malfunctioning

I'm currently using Handlebars as my templating engine for Sailsjs. While basic templating is functioning properly, I'm encountering difficulties when attempting to utilize Handlebars helper functions. Even the built-in functions seem to be unava ...

Encountering a problem with utilizing the equalTo() method in Firebase Realtime Database in a React

I'm having trouble randomizing and querying a specific node in my database based on the ShopNo When I use equalTo, I can't seem to retrieve the desired node. Instead, I'm only getting a randomized value based on the total number of Shop ent ...

Deactivate the linear x axis labels in jQChart

I have a jQchart Linear chart that is displaying correctly and functioning properly. I am looking to remove or disable the X axis labels from the chart. ...

How can a Chrome extension transfer an ArrayBuffer or Blob from a content script to the background script without compromising its data type?

In my current script, I am downloading binary data using XHR in the content script and sending it to the background script: let me = this; let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.responseType = 'arraybuffer'; xhr.onlo ...

Display all keys and values in a dynamically populated object on my screen - React

I have a dynamic object with nested objects, and I want to display every key and value. Even if there are objects within the main object, I need to show their keys and values as well. Here is an example of the object: info:{ address:{ city: {__o ...

Save the current time and date to a database by executing a mysql_query

<form action="actionMAppointment.php?stu_id=<?php echo $row_RecEdit['stu_id'] ?>" method="post"> Time: <input type = "time" name="appointmentTime" id = "appointmentTime" /> Date: <input type = ...

Exploring the intricacies of defining Vue component props in TypeScript using Vue.extend()

Here is a simple example to illustrate my question When I directly define my props inside the component, everything works fine <script lang="ts"> import Vue, { PropType } from "vue"; export default Vue.extend({ props: { col ...

Cropped portion of the captcha image located on the left side

edit: I manually adjusted cnv.width = this.width to 120 and it seems to be working. Upon closer inspection, I discovered that the image has both a rendered size and an intrinsic size. The width is 35 for rendered size and 40 for intrinsic size, which may e ...

Issues with the navigator.contacts.find function occurring when using cordova or phonegap

I am attempting to retrieve the contacts stored on a mobile device. The code snippet I am using is not functioning as expected - specifically, the navigator.contacts.find method isn't producing any outcomes. There are no error messages or success conf ...

The style from 'http://localhost:2000/cssFile/style.css' was rejected because its MIME type was 'text/html'

Currently, I am attempting to include my style.css file in the home.ejs file being rendered by express.js. However, I keep encountering the following error: Refused to apply style from 'http://localhost:2000/cssFile/style.css' because its MIME t ...