Combine various arrays of objects into one consolidated object

Problem: There are untyped objects returned with over 100 different possible keys. I aim to restructure all error objects, regardless of type, into a singular object.

const data = [
    {
        "type":"cat",
        "errors":[
            {
                "keyA":"This is wrong!",
                "keyB":"This is more wrong!!",
                "keyC":"...horrible, just horrible"
            }
        ]
    },
    {
        "type":"dog",
        "errors":[
            {
                "key1":"whoops",
                "key2":"somebody has a typo"
            },
            {
                "keyX":"umm...really?",
                "keyY":"when did it start raining?"
            }
        ]
    }
]

expected result =


            {
                "keyA":"This is wrong!",
                "keyB":"This is more wrong!!",
                "keyC":"...horrible, just horrible",
                "key1":"whoops",
                "key2":"somebody has a typo",
                "keyX":"umm...really?",
                "keyY":"when did it start raining?"
            }

My current solution (which is functional) appears as follows. However, I believe there may be a simpler approach that does not require additional reduce functions. Any suggestions?


const output = input.reduce((acc, curr) => {
    return ([...acc.errors, ...curr.errors] as any).reduce((a: any, c: any) => ({...a, ...c}), {});
});

Answer №1

To achieve an array of objects using Array.flatMap(), followed by merging them into a single object by spreading with Object.assign():

const data = [{"type":"cat","issues":[{"keyA":"This is incorrect!","keyB":"This is even more wrong!!","keyC":"...absolutely terrible"}]},{"type":"dog","issues":[{"key1":"oops","key2":"someone made a mistake"},{"keyX":"uh oh...seriously?","keyY":"when did the rain start?"}]}]

const result = Object.assign({}, ...data.flatMap(obj => obj.issues))

console.log(result)

In TypeScript, it's essential to provide a general type for the object because the issues property contains unspecified properties (TS playground):

interface DataObject {
  type: string;
  issues: Record<string, string>[]
}

const data: DataObject[] = [{"type":"cat","errors":[{"keyA":"This is wrong!","keyB":"This is more wrong!!","keyC":"...horrible, just horrible"}]},{"type":"dog","errors":[{"key1":"whoops","key2":"somebody has a typo"},{"keyX":"umm...really?","keyY":"when did it start raining?"}]}]

const result = Object.assign({}, ...data.flatMap(obj => obj.issues))

console.log(result)

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

Is there a way to utilize a cookie in order for the website to recognize that I have already agreed to the terms?

It's common for websites to ask for cookie and privacy acceptance upon loading, especially in the EU. I'm looking for a way to automatically accept these cookies so I don't have to constantly click "accept all" every time I open Chrome. My ...

Encountered "Function undefined error when invoking within a map in TypeScript"

In my function, there is a map that looks like this: mainFunc(){ // other logics data.map(function (item) { item.number = Math.round(item.number); item.total = item.last - item.first; item.quantity= item?.quantity ? quantityRange(ite ...

When it comes to adjusting the height of an element, there are two ways to go about it: using $(element).height

function adjustHeight(){ var headerHeight=$(element).find('.header').outerHeight(); console.log(headerHeight); var temp=$(window).height()-headerHeight; console.log(temp); $('.users ...

Eradicate lines that are empty

I have a list of user roles that I need to display in a dropdown menu: export enum UserRoleType { masterAdmin = 'ROLE_MASTER_ADMIN' merchantAdmin = 'ROLE_MERCHANT_ADMIN' resellerAdmin = 'ROLE_RESELLER_ADMIN' } export c ...

Navigating through an array in Pug

I'm currently extracting data from an external API in JSON format and sending it to my view. The main issue I'm facing is that one of the properties within the Object consists of an Array of Objects. Using the Pug Documentation for iteration, I&a ...

Using a div in React to create a vertical gap between two React elements

I am working with two React Components in my project - the Right Column and the Left Column. I am trying to create space between them using a div tag. Currently, my setup in the App.js file looks like this: import React from 'react'; import LeftC ...

A new long polling AJAX request is triggered whenever there is a change in the parameter

function AjaxRequest(params, url) { if (params) { this.params = params; this.type = "GET"; this.url = url; // this.contentType = "multipart/form-data"; this.contentLength = params.length;; } } AjaxRequ ...

Tips for accessing a new variable within an array of objects using JavaScript

How can I retrieve a new variable (section) after every 3 objects are called from an array in JavaScript ES6 Map? I've attempted to do this with an ES6 Map, but I'm not achieving the desired result. Can someone please assist me? Thank you! Below ...

Retrieve data from a web api at regular intervals using Angular observables and subscription

My Launch method is designed to start an engine by taking parameters and returning the instance name once started. After that, I need to periodically query another service every 2 seconds to check if the status has changed to either "Succeeded" or "Faile ...

What is the best way to modify the nested state of a dynamically generated state with the useState hook?

I'm currently facing a challenge when trying to update a nested property of a useState object. Here's the specific scenario: In the component, there is a prop "order" that contains multiple items (line_items) which represent the products in th ...

NodeJS reports an invalid key length, while C# accepts the key length as valid

Currently, I am in the process of converting Rijndael decryption from C# to NodeJS. The Key (or Passphrase) being used is 13 characters long, while the IV used is 17 characters long. Note: The length choice for both Key and IV is beyond my control Disp ...

What steps can I take to prevent the [Vue warn]: Potential infinite update loop detected in a component render function issue in my VueJS project?

What are some tips to prevent an infinite update loop in a component render function using VUEJS? I have created a simple show password button with the following structure: <div class="mt-4 switchContainerGenPassword"> <div class="switchGene ...

Iterate through each element in the array and manipulate the corresponding data

I am trying to figure out a way to assign a unique id to each item in an array and send it to the "script.js" file for individual data processing. <script href="script.js"></sciprt> script.js: $(function(){ $('#box' ...

Having trouble understanding why my JavaScript for loop is looping only once

I'm having trouble getting my for loop to output each character of a string argument one at a time. However, when I test the code, it only displays the first character and then stops. I'm not sure what is causing it to only loop through once. Be ...

Ways to specifically load a script for Firefox browsers

How can I load a script file specifically for FireFox? For example: <script src="js/script.js"></script> <script src="js/scriptFF.js"></script> - is this only for Firefox?? UPDATE This is how I did it: <script> if($. ...

Transferring information from offspring to parent

Greetings! I'm currently getting my feet wet with React and finding myself stuck on an issue regarding passing states. Is it possible for me to pass a child state to a parent component in order to selectively render other child components? ...

Tips for efficiently utilizing Hooks with React Context:

I am currently working on my application and utilizing React Context with the setState function. const userContext = React.createContext([{ user: {} }, () => {}]); const userHook = useState({ user: {} }); <userContext.Provider value={userHook}> / ...

How can I remove unnecessary components from an API result in discord.js before sending it?

The particular API being discussed is a pun-themed one, specifically this one. Here is the code snippet I am currently utilizing: const superagent = require("superagent") module.exports = { run: async(client, message, args) => { const pun = a ...

Manage YouTube video played within html code

I am working on a page that contains a YouTube video embedded in HTML. I am trying to find a way to stop the video when it is closed using the YouTube API, but so far my attempts have been unsuccessful. I have included SWFObject and jQuery in the code, yet ...

I'm struggling to understand how to insert the JSON response into an HTML element

I am encountering an issue with my code where the response from the API call is not displaying on the HTML page. I'm unsure why it's not showing up even though the page loads successfully. <!DOCTYPE html> <html> <head> <title ...