Using es6 map to deconstruct an array inside an object and returning it

I am looking to optimize my code by returning a deconstructed array that only contains individual elements instead of nested arrays.

const data = [
{
    title: 'amsterdam',
    components: [
      {
        id: 1,
        name: 'yanick',    
      },
      {
        id: 2,
        name: 'ronald',    
      },
    ],  
  },
  
  {
    title: 'rotterdam',
    components: [
      {
        id: 4,
        name: 'nicky',    
      },
      {
        id: 3,
        name: 'casper',    
      },
    ],  
  },
];

const test = data
  .map(item => {
    console.log(item.components);
    return item.components;
  }).map(array => {
  // how to get comibned components here?
    // it can't use ...item.components (deconstructing or something)
  });
  
console.log('test', test);

My goal is to utilize chained map functions in order to consolidate all elements from item.components into a single array. Is this achievable? It appears that I am unable to destructure the array of each item individually.

Answer №1

The perfect method to apply in this scenario appears to be <code>Array.prototype.reduce
.

const result = numbers.reduce( (finalResult, currentNumber) => finalResult.concat(currentNumber.digits) , []);

console.log('result', result);

Output

result [ { digit: 1, value: 'one' },
  { digit: 2, value: 'two' },
  { digit: 4, value: 'four' },
  { digit: 3, value: 'three' } ]

Answer №2

Retrieve the elements utilizing Array.map(), then combine them by spreading into Array.concat():

const data = [{"title":"paris","elements":[{"id":1,"name":"sophie"},{"id":2,"name":"lucas"}]},{"title":"berlin","elements":[{"id":4,"name":"max"},{"id":3,"name":"mila"}]}];

const output = [].concat(...data.map(obj => obj.elements));

console.log(output);

Answer №3

If you want to consolidate data into a single array, you can utilize the reduce function along with concat to merge all results into one array.

const data = [
{
    title: 'amsterdam',
    components: [
      {
        id: 1,
        name: 'yanick',
      },
      {
        id: 2,
        name: 'ronald',
      },
    ],
  },

  {
    title: 'rotterdam',
    components: [
      {
        id: 4,
        name: 'nicky',
      },
      {
        id: 3,
        name: 'casper',
      },
    ],
  },
];

const test = data
  .map(item => {
    return item.components;
  }).reduce((res, item) => {
    return res.concat(item);
  }, []);

console.log('test', test);

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

Developing a MySQL Community Server-backed RESTful Web Service with the power of jQuery AJAX

I am currently in the process of developing a RESTful Web Service using MySQL Community Server alongside jQuery AJAX Unfortunately, my usage of jQuery AJAX is not functioning as expected. When attempting to add, delete, update a product, or retrieve all p ...

What is a way to automatically run a function at specific intervals in PHP, similar to the setTimeout() function in JavaScript?

I have a JavaScript code snippet that looks like this: setTimeout('$.ajaxCall("notification.update", "", "GET");', 1000); Now, I want to execute the following PHP function every 1000 milliseconds, similar to the above JavaScript code: $notific ...

Creating images or PDFs from HTML with CSS filters: a guide

Looking for someone who has experience creating images or PDFs from HTML code. The HTML contains images with CSS filters such as sepia and grayscale. If you have worked on this type of project before, I would love to hear about your experience. <img cl ...

During the iterations, my array only retains values temporarily. Once the process is complete and I attempt to access those values, it unfortunately returns Null values

After numerous attempts to retrieve values from my array post storing them during iterations, all I get back is a null value. Frustrated and out of ideas, I turned to Stack Overflow in hopes of finding a solution at last. public class RegisterUser extend ...

Mapping an array of objects within another array of objects

I have a collection of objects that I looped through to extract the content: const teamSliderContent = [ { Description1: 'Chef. Mordy Wenk', Title: 'Head of the Chief staff.', id: 1, }, { Desc ...

Is there a way to transform this pledge back into a JSON array format?

My goal with this code is to retrieve a JSON array from my server. var students_list; const library_address = 'http://localhost:17330' async function fetchData(param1, param2) { if(param1 == 'getdata') { const response ...

Encountering an error when attempting to access the 'path' property of undefined from a user-defined input file in Bootstrap 4

I'm currently working on a form that includes a custom input group for selecting a local image file. Unfortunately, I am having trouble retrieving the file name in my server code. Despite checking req.body and trying req.file.path, I have been unable ...

Scrolling through four limited list items automatically

Hey there! I am currently working on a design project. You can check it out here. I'm trying to replicate a section from another site, which you can see here. <div class="latest-winners-container"> <h3 class="header">Latest Winners< ...

Is it possible in Swift to determine the type of an Element in an Array and then utilize it to define the generic type argument?

In my coding project, I've defined a protocol called APIRequest which includes an associated type called ResponseType and a decode function. While the example provided here is not exhaustive, it covers the essential components needed for this discussi ...

Ensure that the React Material UI Textfield with the type "number" is validated to have exactly 10 characters

<TextField variant="outlined" required fullWidth id="accno" label="Main Account Number" type="number" name="accno" //inputProps={{ className:"input-acc", pattern: "^.{0,10}$"}} autoComplete="accno" onChange={(e) = ...

What is the approach to initiating a jquery function once HTML content is dynamically added through an AJAX call?

<div id="timeline"> <ul class="grow" id="grown"><li>One</li><li>Two</li><li>Three</li><li>Four</li><li>Five</li><li>Six</li><li>Seven</li><li>Eight< ...

Merge two scripts together

I'm facing an issue with my frontend due to having two separate scripts in my Vue.js component class. How can I merge them into one cohesive script? If the problem stems from elsewhere, what could it be? <script> import GETUSER from "@/graphql/ ...

Custom sample rate options in RecordRTC allow for the recording of silent audio tracks

I am currently working on implementing RecordRTC.js to capture audio from a microphone and then upload it to a server built with nancyfx. Initially, I am simply aiming to upload the audio stream and store it in a wav file for testing purposes. However, my ...

Correcting the reference to "/" (root) for assets after relocating the site to a subdirectory

I currently have a website located in the public_html directory, where all assets (images, css, js, etc) are referenced using /asset_folder/asset. The "/" at the beginning ensures that the browser starts from the root and navigates through the directories. ...

Storing data from PHP in Local Storage using JavaScript variable

When a specific build name is clicked, the inner HTML content is captured and assigned to a JavaScript variable called loadDump. This variable is then sent over to PHP via an AJAX request. $.ajax({ url:"http://custom-assembly.tcad.co.uk/wp-content/t ...

What is the method to design a file upload feature without a specific form using JavaScript?

I am currently working on a form that handles file uploads using jQuery and AJAX. The goal is to upload the files individually as JSON containing base64 data. Rather than uploading all the images at once, I want each image to be treated as if it were in it ...

Unable to successfully export ExpressJS routes to an external file when targeting the root path

I am seeking a way to organize my routes by exporting them into external files. Currently, all routes except the root route are functioning correctly: localhost/login -> "Login page" localhost/ -> empty server.js: // SERVER SETUP ============= v ...

retrieving the current value of a variable from a jQuery function

I've done my best to keep things simple. Here's the HTML code I've put together: <div id="outsideCounter"><p></p></div> <div id="clickToAdd"><p>Click me</p></div> <div id="in ...

Any property modified by an event handler will consistently appear in its original form

Every second, a simple function is called using setInterval, with the goal of determining mouse or keyboard activity. The variable that tracks the activity is updated, but it always remains set to 0 despite the fact that console.log statements are being e ...

How can permissions for video and audio be configured in Next.js?

When the button is clicked, I want to set permissions. This is how I'd like the scenario to play out: first, the method works initially and allows permission when the button is pressed. Here is my code: <button onClick={requestPermission} classN ...