How can you combine multiple arrays of nested objects in ES6?

Here is an example array I have:

[
  {
    data: [
      { a: "a", b: "b" },
      { x: "x", y: "y" },
    ],
  },
  {
    data: [
      { c: "c", d: "d" },
      { z: "z", f: "f" },
    ],
  },
  {
    data: [
      { d: "d", e: "e" },
      { g: "g", h: "h" },
    ],
  },
];

I am looking to merge all items in the 'data' arrays into one single array, resulting in:

[
  { a: "a", b: "b" },
  { x: "x", y: "y" },
  { c: "c", d: "d" },
  { z: "z", f: "f" },
  { d: "d", e: "e" },
  { g: "g", h: "h" },
];

I prefer not to use lodash as suggested in other questions, and would like to achieve this using only ES6 features.

Answer №1

By utilizing the power of Array.prototype.flatMap, you can consolidate all data items into a single array.

const input = [
  {
    data: [
      { a: "a", b: "b" },
      { x: "x", y: "y" },
    ],
  },
  {
    data: [
      { c: "c", d: "d" },
      { z: "z", f: "f" },
    ],
  },
  {
    data: [
      { d: "d", e: "e" },
      { g: "g", h: "h" },
    ],
  },
];

const output = input.flatMap((item) => item.data);
console.log(output);

Answer №2

If you are in search of the following:

const elements = [
  {
    items: [
      { name: "John", age: 25 },
      { name: "Jane", age: 30 },
    ],
  },
  {
    items: [
      { color: "red", size: "small" },
      { color: "blue", size: "large" },
    ],
  },
  {
    items: [
      { fruit: "apple", taste: "sweet" },
      { fruit: "banana", taste: "tangy" },
    ],
  },
];

const result = elements.map(e => e.items).flat();
console.log(result)

Answer №3

const information = [
  {
    details: [
      { name: "Alice", age: 30 },
      { city: "New York", country: "USA" },
    ],
  },
  {
    details: [
      { name: "Bob", age: 25 },
      { city: "London", country: "UK" },
    ],
  },
  {
    details: [
      { name: "Charlie", age: 35 },
      { city: "Sydney", country: "Australia" },
    ],
  },
];

let combinedData = []
let newDataSet = information.map(item => item.details.map(entry => combinedData.push(entry)))
console.log(combinedData)

Answer №4

Utilize the array reduce function.

let b = [
  {
    info: [
      { first: "first", second: "second" },
      { red: "red", blue: "blue" },
    ],
  },
  {
    info: [
      { one: "one", two: "two" },
      { green: "green", yellow: "yellow" },
    ],
  },
  {
    info: [
      { three: "three", four: "four" },
      { orange: "orange", purple: "purple" },
    ],
  },
];

let result = b.reduce((previous, current) => previous.concat(current.info), []);
console.log(result);

Answer №5

One efficient method is to utilize the reduce function along with the spread operator:

const arr = [
  {
    data: [
      { a: "a", b: "b" },
      { x: "x", y: "y" },
    ],
  },
  {
    data: [
      { c: "c", d: "d" },
      { z: "z", f: "f" },
    ],
  },
  {
    data: [
      { d: "d", e: "e" },
      { g: "g", h: "h" },
    ],
  },
];

const newArr = arr.reduce((acc, rec) => [...acc, ...rec.data], [])

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

"Extracting regular expressions between the penultimate and ultimate characters

I'm struggling with a simple regex question. I want to extract text between two specific characters: - and ~ Here's my string: Champions tour - To Win1 - To Win2 ~JIM FURYK Currently, when I use this regex pattern: \-([^)]+\~), it mat ...

Error in bundle.js at line 25872: A critical error has occurred due to excessive re-renders. React has imposed a limit on the number of renders to avoid an infinite loop. Learn how to resolve

I am currently working on CRUD operations to update data. How can I avoid this error: "Too many re-renders. React limits the number of renders to prevent an infinite loop?" import React,{useEffect,useState} from 'react'; import { NavLink } from ...

Create an interactive list with the ability to be edited using HTML and

I'm currently working on a UI scenario that involves a text box field with two buttons beneath it. When the user clicks the first button, a popup will appear prompting them to input an IP address. Upon submitting the IP address in the popup, it will b ...

Error loading code. Works when manually pasted, but not when executed with JavaScript

After some trial and error, I found that this code works perfectly if I manually copy the content from the class isotope in 1.php to the class grid on this page. However, when I try to use JS to do the same thing, it mysteriously stops working. Any sugge ...

Is the node certificate store limited to reading only from a predefined list of certificates?

Is there a way to add a new certificate to the list of certificates node trusts, even after some struggle? It appears that Node only trusts certificates hardcoded in its list located here: https://github.com/nodejs/node/blob/master/src/node_root_certs.h ...

Organize the array by property name and include a tally for each group

My current data structure looks like this: var data = [ { MainHeader: Header1, SubHeader: 'one'}, { MainHeader: Header1, SubHeader: 'two'}, { MainHeader: Header2, SubHeader: 'three'}, { MainHeader: Header2, SubHea ...

Displaying the second image twice in a jQuery image slider

When attempting to implement a slider on my website, I encountered an issue where the second image appears twice in a row before the slider starts working as expected. I'm struggling to figure out why this is happening. Here is the jQuery code I am u ...

Encountering difficulties in importing TailwindCSS

Having trouble importing TailwindCSS and applying CSS? Here's how it's included in my package.json: "devDependencies": { "autoprefixer": "^10.2.4", "css-loader": "^5.1.1", "postc ...

What is the best way to compare two date strings with the format dd/mm/yyyy using JavaScript?

When attempting to compare a "Date" type of data with an "Any" type of data, the comparison is not functioning as expected. The date is retrieved in the following code: var today = new Date(); var dd = String(today.getDate()).padStart(2, '0'); v ...

Estimating Dates Using Javascript and JSON

I am currently working on visualizing some data I have. You can view the fiddle here: http://jsfiddle.net/hohenheim/6R7mu/10/ As part of this visualization, I have extracted a small subset of the JSON data that I am trying to represent, named data2. Here ...

Illuminate a corresponding regular expression within a text input

I currently have a functional code for testing regex, which highlights matching patterns. However, my challenge lies in highlighting the result within the same input as the test string. Below you will see the HTML and JavaScript snippets along with two ima ...

The filter is displaying incorrect categories

I am facing an issue with creating a work filter based on the last column which represents categories. When I select an option from the dropdown, I want to display only that specific category and hide the others. Currently, when I try clicking on an option ...

Proceed with executing the function only if the current date is before the specified date

I've created a countdown timer that can count both up and down from a given date. However, I want the countdown to only run in reverse and stop once it reaches the current date or any future dates. Currently, the alert message shows when the date is r ...

Getting a boolean response from an asynchronous SQLite query in Express

I am currently developing a middleware that verifies the validity of a session (meaning it has a logged-in user attached). For this purpose, I am utilizing sqlite3 for node.js. Since I am not very familiar with JavaScript, I am facing some challenges figu ...

Encountered an uncaughtException in Node.js and mongoDB: User model cannot be overwritten once compiled

Currently, I am utilizing this import statement const User = require("./Usermodel")' However, I would like to modify it to const User = require("./UserModel") Despite my efforts to align the spelling of the import with my other i ...

Display or conceal specific fields depending on the selection from a dropdown menu

I'm currently experimenting with using JavaScript and/or jQuery to dynamically hide specific HTML elements based on the selection in a drop down menu. Here is what my page setup looks like: [Drop down menu] [text field 1] [text field 2] [text field ...

What is the best way to integrate Express JS with Google Charts?

I'm currently working on an Express application and I need to integrate Google charts into it. I found this helpful article here for guidance. Additionally, I would like to know how to replace manual data with data from a MySQL database. ...

Using three.js to establish an Image for Particle

I am looking to make some changes to this demo: Instead of having colored particles, I want to assign an image to each one. Should I use a cube for this purpose? Or is there a way to use an image with Vector3? Here is the code for the example: i ...

Using jQuery to clear a textarea when a select input is changed

Currently, I am in the process of developing a small text editor that enables users to edit files and create new ones. Here is how I have set up my select menu. <select name="reportname" id="reportname" class="form-control"> <option value="zr ...

Update header component dynamically upon successful login with Angular 11

I am currently using Angular 11 and facing an issue with displaying the username in the header component. The header loads before the login component, which results in the user data being stored in local storage only after the login component is loaded. As ...