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

The conversion of string to number is not getting displayed correctly when using console.log or document.write. Additionally, the concatenated display is also not functioning as intended

Being new to JS and HTML, this program was created to enhance my understanding of the concepts. I attempted a basic program to convert a string to a number in three different ways, but I am having trouble determining if the conversion actually took place. ...

Azure SQL Server linked with a REST API built on Express.js/Node.js encountered an error stating: "TypeError: req.sql is not a function"

Having trouble connecting to Azure SQL Server with express4-tedious. I'm working on building an app in react-native with a Node/Express server (REST API), but encountered this error after setting up express4-tedios in Express: req.sql is not a functio ...

Injecting services differently in specific scenarios in AngularJS

I have a unique angular service called $superService that I utilize across many of my directives and controllers. However, there is one specific directive where I want to implement the following behavior: If another directive utilizes $superService in its ...

Advantages of utilizing bracket notation (alongside variables) for retrieving a property from an object

When it comes to accessing stored information, utilizing alternatives like the dot operator can be straightforward. However, Iā€™m struggling to grasp the significance of using variables in achieving the same goal. For instance: var myObj = { prop1: "v ...

Building a Div Tag Layout with CSS for Full Width and Left Position of 300px

Experiencing some trouble with styling a div element. My goal is to have the div start at left:300px and stretch across the entire width of the browser window. However, when I apply width:100%, the div extends beyond the boundaries of the browser screen. ...

Collaborate and reuse Typescript code across various Node projects

Imagine we have a project structured like this: webapps ProjectA SomeClass.ts Package.json ProjectB SomeClass.ts Package.json Common LoggingClass.ts Package.json The Common "LoggingClass" needs to import a module from NPM. Let's say that ...

Leverage the power of npm packages within a Flutter mobile app's webview

I am currently developing a Flutter mobile app and I am interested in incorporating an npm package that utilizes web3.js and offers additional custom features. My understanding is that Dart code in Flutter is not compiled to JavaScript, so I have been lo ...

Using Backbone to Retrieve a JSON File from a Server: Deciding Whether to Include the File Extension ".json" in the URL or URLRoot

Exploring Backbone with exercise by trying to obtain a JSON file from the server using the urlRoot property of the Model. Encountered an error (404) when setting urlRoot: "./js/json/todo", paths with ".json" work but console.log(todoItem.get('descrip ...

The data-src tags are functioning properly in the index.html file, but they are not working correctly in angular

I'm still learning about Angular and JavaScript, so please bear with me if my questions seem silly. I've been trying to add a theme to my Angular project. When I include the entire code in index.html, everything works fine. However, when I move ...

The child div can be scrolled horizontally, while the parent window remains fixed

I am facing a challenge with my HTML and CSS setup. I want to create a child div that scrolls horizontally, but I do not want the parent window to scroll along with it. Below is my current code: <div id="parent"> <div id="div1"> . ...

Issues with Weglot link hooks not functioning properly within the sticky header

I have integrated Weglot for translations on my website, aigle.ca. Due to issues with their widget, I am using link hooks instead. You can find more information about link hooks at: weglot.com link-hooks However, when scrolling down the page and the menu ...

Data is not loaded until after the HTML for the Nuxt page has been

My issue is that I have a dynamic page where product details are loaded, but the html code loads before the data. This results in errors when trying to use static elements like images because the "product" object does not exist. To address this problem, I ...

Conceal the div with ID "en" if the value matches $en

Looking for assistance with language settings on my page. I have a menu where I can select English, Croatian, or German. Below is the code to manage language changes: <?php class home_header_language { protected $_DBconn; ...

extract data from a JSON-formatted object

While developing my asp.Net application using MVC 3, I encountered a situation in which I was working with a jQuery control. I received a JSON response that looked like this: { "text":"Books", "state":"open", "attributes":{ ...

Looking for a way to detect changes in a select menu using Angular?

How can I determine with the openedChange event if there have been any changes to the select box items when the mat select panel is closed or opened? Currently, I am only able to detect if the panel is open or closed. I would like to be able to detect any ...

Adjust properties based on screen size with server-side rendering compatibility

I'm currently using the alpha branch of material-ui@v5. At the moment, I have developed a custom Timeline component that functions like this: const CustomTimeline = () => { const mdDown = useMediaQuery(theme => theme.breakpoints.down("md")); ...

I cannot seem to locate the module npm file

Currently, I am in the process of following a Pluralsight tutorial. The instructor instructed to type 'npm install' on the terminal which resulted in the installation of a file named npm module in the specified folder. However, when I attempted t ...

Using PHP variables in JavaScript is not compatible

Currently, I am facing an issue where PHP variables inside the javascript code are not being echoed. When I try to echo the variables outside of the javascript, everything works perfectly fine. After carefully reviewing my code multiple times, I still cann ...

Experiencing difficulty in transferring array information from a parent component to a child component within an

I'm currently working on a task where I need to pass data from a parent component to a child component. The data consists of an array that is nested within another array. parent.component.html <div *ngFor="let parent of parentArray; index as ...

Fragment errors detected in the Menu Component

I am facing an issue with my code where I am getting an error in the console saying that the Component cannot receive fragments as children. How can I remove the fragments while retaining the logic? Every time I attempt to remove the fragments, I encounter ...