Converting Typescript objects containing arrays into a single array

Looking for some assistance with this problem :)

I am trying to convert the object into an array with the following expected result:

result = [
  {
    id: 'test-1',
    message: 'test#1.1'
  },
  {
    id: 'test-1',
    message: 'test#1.2'
  },
  {
    id: 'test-2',
    message: 'test#2.1'
  },
  {
    id: 'test-2',
    message: 'test#2.2'
  }
]

I attempted using Object.keys() and map(), but it did not produce the desired outcome as shown below:

mockData = {
  'test-1': [
    {
      message: 'test#1.1'
    },
    {
      message: 'test#1.2'
    }
  ],
  'test-2': [
    {
      message: 'test#2.1'
    },
    {
      message: 'test#2.2'
    }
  ]
}

const result = Object.keys(this.mockData).map((id) => {
  return {
    id,
    ...this.mockData[id],
  }
})

console.log(result)

Do I need to add another map() over this.mockData[id]? What mistake am I making, and what would be the best practice in this situation (maybe reduce()?)?

Your help is greatly appreciated!

Answer №1

To separate a grouped object into individual elements, you can employ the flatMap method with the Object.entries function and utilize nested map() functions.

const data = { 'group-1': [{ item: 'group#1.1' }, { item: 'group#1.2' }], 'group-2': [{ item: 'group#2.1' }, { item: 'group#2.2' }] };

const result = Object.entries(data).flatMap(([key, values]) => values.map(value => ({ key, ...value })));

console.log(result);

Alternatively, you can opt for a for...of loop approach

const data = { 'group-1': [{ item: 'group#1.1' }, { item: 'group#1.2' }], 'group-2': [{ item: 'group#2.1' }, { item: 'group#2.2' }] };

const result = [];
for (const [key, items] of Object.entries(data)) {
  for (const item of items) {
    result.push({ key, ...item });
  }
}

console.log(result);

Answer №2

Here is the solution you've been seeking:

let newArray = [];
Object.keys(mockData).forEach((key) => {
    mockData[key].forEach((data) => {
        newArray.push({
            id: key, 
            message: data.message
        })
    })
})

Answer №3

Using the Object.keys method on mockData to iterate through its properties, then mapping over each property to create a new array of objects with the id added as a key using ES6 spread syntax, and finally flattening the nested arrays into one flat array.

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

Discover the steps to activate and utilize mat-error without the need for form control manipulation

Have you encountered an issue with using ngModel and mat-error without a form? Is there a workaround that allows the use of mat-error with ngModel? #code <mat-form-field appearance="fill" class="w-48per"> <mat-label>Fi ...

Ways to resolve the issue of BrowserWindow not being recognized as a constructor when trying to create a child window within the Electron

Currently, I am utilizing electron to construct an application with two windows. In my attempt to open a second window from the renderer process, I have implemented the following code snippet: const electron = require('electron'); const BrowserW ...

Retrieve components of Node.js Express response using axios before terminating with end()

Is there a way to receive parts of a response from my nodejs server before res.end() using axios? Example: Server router.get('/bulkRes', (req,res)=>{ res.write("First"); setTimeout(()=>{ res.end("Done"); },5000); }) Cl ...

Preserve HTML element states upon refreshing the page

On my webpage, I have draggable and resizable DIVs that I want to save the state of so they remain the same after a page refresh. This functionality is seen in features like Facebook chat where open windows remain open even after refreshing the page. Can ...

Learn how to assign an ID to a React component in order to access it using the document.getElementById() method

After going through multiple inquiries, my understanding led me to believe that simply setting the id as shown below would suffice: <MyComponent id="myId"/> However, upon invoking document.getElementById() on the specified id, I receive a null resu ...

Creating a function to update data in a Node.js/MongoDB environment

Hey there! I'm new to working with nodejs and mongodb, and I'm trying to create a function that updates the win, lose, and draw record in my UserSchema. Here's my Schema: UserSchema = new mongoose.Schema({ username:'string', ...

Obtaining multiple values: Utilizing array versus modifying referenced parameters

Whenever I need to return multiple values as a result of my function (for example, a boolean indicating the success of a specific operation and a message detailing the error or success message), I often ponder the most effective method. Should these multip ...

Shift the content downwards within an 'a' snippet located in the sidebar when it reaches the edge of the right border

I'm having an issue with my style.css file. As a beginner in programming, I am trying to position text next to an image attached in the sidebar. However, the text is overflowing past the border. Here's the HTML code: Please see this first to ide ...

Store the image URL in cache during AJAX loading

I have implemented an ajax slider to display images, and it is functioning perfectly. However, I am facing an issue with image caching. Since the images change dynamically using ajax, there is no cache available which causes a delay in displaying the new i ...

What is the correct way to pass a 2-dimensional array from Python to Postgres?

I need assistance with inserting a 2-dimensional numeric array in Postgres. The SQL query to achieve this is: INSERT INTO student (studentScore) VALUES ('{ {"1", "21.0"}, {"2", "22.0"}, {"3", "4 ...

Retrieve returned data using jQuery

How can I retrieve data when using the jQuery.get method? function send_data(pgId) { for(var i = 0; i < pgId.length; i++) { // $.get(url, data, success(data, textStatus, jqXHR)) $.get('index.php?page=' + pgId[i], pgId[ ...

Issue with Vue 3: Composition API does not support Array of refs

Check out the code snippet below. <template> <div v-for="item in arr" :key="item">{{ item }}</div> </template> <script> import { ref } from "vue"; export default { name: "TestArr", ...

Ways to detect when the window printing process has been completed

Within my application, I attempted to generate a voucher page for the user using the following code: var htm ="<div>Voucher Details</div>"; $('#divprint').html(htm); window.setTimeout('window.print()',2000); The &apo ...

What is causing the consistent error message "unable to read property 'logged' of undefined"?

Here is the code snippet from my app.js: var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie- ...

Exploring ways to dynamically alter templates using the link function in Angular.js

Recently, I developed a directive called widget which functions similar to ng-view, but the template name is derived from an attribute. app.directive('widget', function() { return { restrict: 'EA', scope: true, ...

React Router imports and renders multiple components

I'm currently working on developing a basic Login System. When I try to register, both components are loaded into the App Component. Here is my code: class App extends React.Component { render() { return ( <div className="row"> ...

Tips on selecting data from an array to populate a mat-selection-list

When I receive a string like this from the API: 55,118,122,126,116,58,125,119,132. These are the ids that I need to work with in my Angular mat-selection-list. My goal is to initially select these values and update existing data before sending it back thro ...

Can TypeScript be set up to include undefined as a potential type in optional chains?

Today, I encountered a bug that I believe should have been caught by the type system. Let me illustrate with an example: function getModel(): Model { /* ... */ } function processModelName(name: string) { return name.replace('x', 'y& ...

The behavior of the jQuery click function seems to be quirky and not functioning as expected. Additionally, the

It seems that instead of triggering a POST request, somehow a GET request is being triggered. Additionally, the ajax call is not being made as expected. I have attempted this many times before, but none of my attempts seem to be working. It could potenti ...

Is there a way to horizontally navigate a pallet using Next and Prev buttons?

As someone new to development, I am looking for a way to scroll my question pallet up and down based on the question number when I click next and previous buttons. In my pallet div, there are over 200 questions which are dynamically generated. However, th ...