Obtain an array containing only one property value from an array of objects

Within my array of objects, I am looking to extract all the controls and move them to a new array:

this.formModel = {
    sections: [
        {
            title: 'Section 01',
            controls: [
                new FormControlInput({
                    key: 'name 01',
                    label: 'Name 01'
                }),
                new FormControlSelect({
                    key: 'abc',
                    label: 'Abc'
                })
            ]
        },
        {
            title: 'Section 02',
            controls: [
                new FormControlInput({
                    key: 'name 02',
                    label: 'Name 02'
                })
            ]
        }
    ]
};

Although I am attempting to achieve this using map, the result is an array of arrays rather than a single array:

this.formModel.sections.map(function (x) { return x.controls; })

Current output:

[
     {
        [{
            key: 'name 01',
            label: 'Name 01'
        },
        {
            key: 'abc',
            label: 'Abc'
        }]
     },
     {
        [{
            key: 'name 02',
            label: 'Name 02'
        }]
     }
]

What I am aiming for is:

[
    {
        key: 'name 01',
        label: 'Name 01'
    },
    {
        key: 'abc',
        label: 'Abc'
    },
    {
        key: 'name 02',
        label: 'Name 02'
    }       
]

Answer №1

Simply flatten your array after using the map function:

var example = {
  groups: [{
      title: 'Group 01',
      items: [
        { key: 'item 01', label: 'Item 01' },
        { key: 'abc', label: 'Abc' }
      ]
    }, {
      title: 'Group 02',
      items: [
        { key: 'item 02', label: 'Item 02' }
      ]
    }
  ]
};

var mapped = example.groups.map(function (x) { return x.items; });
var flattened = [].concat.apply([], mapped);
console.log(flattened);

To simplify the example:

// Here is the structure:
var groups= [{
      items: [{}, {}] // I1
    }, {
      items: [{}]     // I2
    }
];

// Using map to extract each `items` property and create an array entry for each:
var mapped = groups.map(function (x) { return x.items; });
console.log(mapped);
// [[{},{}],[{}]]
//  ^ I1    ^ I2

// Removing the extra layer of arrays:
var flattened = [].concat.apply([], mapped);
console.log(flattened);

Answer №2

To simplify the structure, employ the `reduce` function

formModel.categories
  .map(item =>  item.items)
  .reduce((previous, current) => previous.concat(current), [])

Answer №3

Replace map with reduce:

let formData = {
    sections: [
        {
            title: 'Section 01',
            controls: [
                {
                    key: 'name 01',
                    label: 'Name 01'
                },
                {
                    key: 'abc',
                    label: 'Abc'
                }
            ]
        },
        {
            title: 'Section 02',
            controls: [
                {
                    key: 'name 02',
                    label: 'Name 02'
                }
            ]
        }
    ]
};

let finalResult = formData.sections.reduce((finalRes, section) => {
return finalRes = finalRes.concat(section.controls); 
}, []);

console.log(finalResult);

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

Having trouble retrieving JSON data from the open weather API

I'm working on a small website to display the weather of a specific city using an API. However, I am facing an issue where I can't seem to display the temperature from the response. Below are snippets of my JavaScript and HTML files: var ap ...

Verify whether an option is chosen in CakePHP 3 form

I'm working on a form where users can select Types and each type has an associated color. In my TypesController, I have a function that retrieves the list of types with their IDs, names, and colors. $types = $this->Types->find('list') ...

The loading bar animation doesn't begin at a blank slate

I'm currently working on a project that utilizes Django for the backend and Bootstrap for the frontend. I have to admit, I am quite inexperienced when it comes to front-end development; JavaScript seems like magic to me. One of the key features I nee ...

Sending form submission data with useFormik via React Router's Link component is a common task in web development. By

My goal is to transfer form data generated through the useFormik and yup hooks to another component using React Router DOM's 'Link' feature. However, I have encountered two issues in this process. Issue 1: I am struggling to pass the useFor ...

Is it possible to dynamically change the color of a box shadow using an event handler?

I'm currently in the process of developing an application that consists of six distinct topics organized within a flexbox structure, complete with a box-shadow effect. My objective is to dynamically alter the color of the box-shadow through an event ...

The logs of both the frontend and backend display an array of numbers, but surprisingly, this data is not stored in the database

I am attempting to recreate the Backup Codes feature of Google by generating four random 8-digit numbers. for(let i = 0; i < 4; i++) { let backendCode = Math.floor(Math.random() * (99999999 - 10000000 + 1) + 10000000); backendCodes.push(back ...

Error encountered when trying to send form data through an AJAX request

Whenever a user updates their profile picture, I need to initiate an ajax call. The ajax call is functioning properly, but the issue lies in nothing being sent to the server. <form action="#" enctype='multipart/form-data' id="avatar-upload-fo ...

The mystery of why gulp-watch fails to remove files

I need help figuring out why my gulp-watch task isn't deleting files from the /dest directory when I delete them from /src. Can someone spot the issue? var watch = require('gulp-watch'); var imagemin = require('gulp-imagemin'); ...

Managing Visual Studio Code Extension Intellisense: A Guide

I am looking to create an extension I recommend using "CompletionList" for users. Users can trigger completion by running "editor.action.triggerSuggest" The process of my extensions is as follows: Users input text If they press the "completion command," ...

Method for extracting URL parameters while utilizing a hash within the URL

I've been exploring AJAX with hash in URL using prototypejs. Consider the following URL: http://example.com/#/example/104?v=0&d=a&rpp=10 print_r( $_GET ); // output: array() However, when I try this URL: http://example.com/example/104?v= ...

The execution of async.each does not complete successfully

I'm facing an issue with a simple function that retrieves the word count from a URL. The script runs smoothly with a low number of URLs, limiting the async to 4 at a time. I keep an eye on my RAM and CPU usage, but they never come close to maxing out. ...

Display Angular elements within dynamically injected HTML

I am facing an issue with my Angular 15 application. I have a component called FatherComponent, which receives HTML content via an API and injects it into its template using innerHTML: <div [innerHTML]="htmlContent"></div> The proble ...

Implementing Angular Universal on Azure Platform

After converting my application to Angular Universal at the request of my clients, I successfully ran it using npm run serve:ssr and accessed it through http://localhost:4000. Now, the challenge lies in deploying it. Upon running npm run build:ssr, a dist ...

Error: An unexpected symbol '<' was encountered after the build process in Vue.js

I just finished deploying a MEVN stack application to heroku. While everything is functioning properly locally, I am encountering a blank page and the following errors in the console post-deployment: Uncaught SyntaxError: Unexpected token '<' ...

Use Python to fetch a file from a webpage without having to actually open the webpage

I needed a method to automate the download of a file from a particular website without having to manually open the website. Everything should be done in the background. The website in question is Morningstar, and a specific example link is: . On this page ...

Error with React Query Mutation and TypeScript: The argument '{ surgeryID: any; stageTitle: any; }' cannot be assigned to a parameter of type 'void'

Utilizing react-query for fetching and posting data to my database on supabase has been really helpful. I took the initiative to create a custom hook specifically for adding records using react-query: export function useAddSurgeryStage() { const { mutate ...

Error message: Unforeseen node express token problem

Whenever I attempt to call the endpoint provided below, Postman returns an error as shown: { "success": false, "error": "Unexpected token / in JSON at position 7" } Within the addFollowing function, you'll notice that I ...

What is the best way to extract function bodies from a string with JavaScript?

I am currently searching for a solution to extract the body of a function declaration by its name from a JavaScript code string within a Node.js environment. Let's assume we have a file named spaghetti.js that can be read into a string. const allJs = ...

Motion of the atoms

I recently came across an interesting effect on the IconArchive website, but I am unsure how to implement it. If anyone could help me understand the concept with a small example, that would be greatly appreciated. You can see the effect in action by visi ...

Check if the page has been loaded using Jquery

Can anyone share a helpful strategy for initiating a function in JavaScript that only begins once the entire page has finished loading? ...