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

Sending information from the backend to the frontend using Node.js and Express

I am seeking advice on the most effective method for achieving a specific task. In my Node.Js / Express application, there is a point where I need to send data to the backend and receive a certain value back to the front end. Typically, this can be accomp ...

Modify the CSS style of the select label and change the color of the currently selected option in MUI

For the past few days, I've been facing challenges with implementing MUI components while working on a page for a React app. I'm almost finished with my project, but there are 2 key things missing... On my page, I have utilized a Select and an ...

Here is a guide on implementing Hash in URLs with React Router

I'm brand new to React and running into an issue. My page has two tabs and I would like to create a hash URL that will redirect to the corresponding tab based on the URL hash. Additionally, when I change tabs, I want the URL to update as well. Please ...

Can the value in a JavaScript object be updated dynamically when a button is clicked?

In my JavaScript code, there is an object named annualPlan. Whenever a user submits the HTML form for a specific month, I aim to update the value in the object for that particular month accordingly. For instance, if someone submits August 21 and 200, I w ...

struggling to access the value of [(ngModel)] within Angular 6 component

When working in an HTML file, I am using ngModel to retrieve a value that I want to utilize in my component. edit-customer.component.html <input id="userInfoEmail" type="text" class="form-control" value="{{userInfo.email}}" [(ngModel)]="userInfo.email ...

Is there a way to break this down so that I can obtain an array containing the data for each month?

My JSON structure is as follows: "meterConsumption": [ { "month": 1, "details": [ { "timestamp": "2020-01-01", ...

Creating a binary tree in vanilla JavaScript and styling it with HTML and CSS

I'm facing a challenge with my homework. I am required to convert my JavaScript binary tree into HTML and CSS, strictly using vanilla JavaScript without any HTML code. I have the tree structure and a recursive function that adds all the tree elements ...

Dealing with Errors in Angular 8: Best Practices for Handling Response Errors

When an error is thrown from the WEB API, I do not receive any response and the debugger does not hit. However, in case of success, I do get a response and the debugger hits. All I want is to receive an error response and have the debugger hit every time, ...

Vue JS: Extracting both the unique ID and value from an array of input simultaneously

I am new to Vue and currently exploring its capabilities. I am experimenting with the Element UI for Vue's user interface. Specifically, I am working with the Input Number Component, to manage an array of data. Let's assume my data is structured ...

How can typescript configurations be imported/exported in a node environment?

I'm encountering difficulties while trying to set up a TypeScript node project and import modules: Below is the structure of my project: /build /src main.ts ...

Using the Count() function in PHP to update information upon page refresh

I have created a basic cart that displays a div containing purchased items when hovered over. The issue I am facing is that every time I click on the add to cart button, it doesn't immediately update the number of items in the cart. I have to manually ...

Encountering a MiniCssExtractPlugin error while trying to build with npm

I have encountered an issue while trying to execute "Npm Run Build" on my reactjs website. The error message I keep receiving is as follows: /usr/local/lib/node_modules/react-scripts/config/webpack.config.js:664 new MiniCssExtractPlugin({ ^ TypeErr ...

Guide to filling a dropdown menu by aligning with the text it contains?

I've set up two dropdown select boxes below that are exactly the same: HTML <select id="ddl1" name="ddl1"> <option value="1">TEXT 1</option> <option value="2">TEXT 2</option> <option value="3">TEXT 3&l ...

Effortless implementation of list loading with images and text in the Ionic 2 framework

Can someone provide guidance on creating a lazy loading list with both images and text? I understand that each image in the list will require a separate http request to download from the server. Should caching be implemented for these image downloads? Addi ...

The React functional component fails to update when triggered by a parent component's setState method

My React component is utilizing apollo to fetch data through graphql class PopUpForm extends React.Component { constructor () { super() this.state = { shoptitle: "UpdateMe", popupbodyDesc: "UpdateMe" } } re ...

Express is experiencing issues with Angular Universal, preventing it from functioning properly

While attempting to implement Angular Universal in my project, I encountered some issues. Here are the details: 1. ng --version Angular CLI: 9.0.2 Node: 13.5.0 OS: win32 x64 Angular: 9.0.1 ... animations, common, compiler, compiler-cli, core, forms ... ...

Discovering all invalid elements in an Angular 8 Form using Typescript by revealing required fields post button click

Once the button is clicked, I want to retrieve all invalid elements in the Form and showcase those fields that are either incomplete or required. ...

Ajax - Trouble with Updating DIV Content

As a beginner in AJAX, I am encountering difficulties creating a simple AJAX program. My goal is to have a button that, when clicked, changes the text of the div below it. Despite numerous attempts, I have not been able to identify the issue. Below is the ...

Adjust the setting for the useHash parameter within the RouterModule during execution

I am faced with a situation where I need to dynamically load my router module option useHash in my Angular application, sometimes with true and other times with false. This decision depends on the server state data that is available in the global window ob ...

Is there a way to alter a container component depending on a condition without duplicating its content?

As I work with Component A, which serves as a container, I am faced with the challenge of selecting either ComponentA or ComponentB based on certain conditions without duplicating the content. <ComponentA *ngIf=true> ...Content </ComponentA&g ...