What is the best way to retrieve all objects from this data model?

I am looking to collect all the Model Objects from the data structure provided below.

const PRODUCTS = [
    {
        brand: 'Audi',
        allSeries: {
            serie: 'A3',
            allModels: [
                { model: 'A3 1.5 Sportback' },
                { model: 'A3 2.0 TDI' }
            ]
        }
    },
    {
        brand: 'Volkswagen',
        allSeries: {
            serie: 'Golf',
            allModels: [
                { model: 'Golf 1.5' },
                { model: 'Golf 2.0' }
            ]
        }
    }
]

My goal is to combine all the model objects into one array structured like

[{model:'Golf 1.5}, {...}, {...}]
.

Answer №1

One way to achieve this is by utilizing the array's map() method. Give this a try and let me know if it solves your problem:

const PRODUCTS = [{ brand: 'Audi', allSeries: { serie: 'A3', allModels: [ { model: 'A3 1.5 Sportback' }, { model: 'A3 2.0 TDI' } ] } },{ brand: 'Volkswagen', allSeries: { serie: 'Golf', allModels: [ { model: 'Golf 1.5' }, { model: 'Golf 2.0' } ] } }];

const models = PRODUCTS.flatMap(product => product.allSeries.allModels);

console.log(models);

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

Tips for implementing lazy loading for a section of a template in Angular 2

I have an Angular 2 component that has several sub-components within it. Some of these sub-components are expensive to load and may not always be necessary, especially if the user doesn't scroll far enough down the page. Although I am familiar with l ...

Tips on how to retrieve the current value of a scope variable in jQuery

When making a $http request to save data on the server and receiving a json response, I want to show an Android-style message using Toast for either success or failure based on the response. Initially, I set a scope variable to false $scope.showSuccessToa ...

What is the best way to determine the number of elements in a primitive array in Java?

Is there a way to find the count of non-even values in a primitive array in Java, rather than just its length? int[] array = new int[26]; array[0] = 1; array[1] = 2; array[2] = 3; for (int i=0; i<array.length; i++) if (array[i] % 2 != 0) r ...

What steps should I take to resolve npm start issues within my Node.js application?

Upon completing the npm install, I attempted to run npm start for my project. Unfortunately, an error was displayed. What steps can be taken to resolve this issue?view image of the error here ...

Tips for retrieving all JavaScript source links from a website URL during page download

Is there a way to determine if a website is using a specific online JavaScript source, such as fontawesome? Some sources may only become apparent once they are actually loaded, rather than being visible in the website's source HTML. I attempted to us ...

Exploring the Power of D3.js: Loading and Visualizing Multiple Networks using JSON Files and the Force

I have a collection of networks consisting of nodes and links stored in various JSON files. I am using D3.js to load them into a Force Layout, where they each load and layout perfectly when loaded individually. However, I would like to enhance the function ...

Transforming rows into a JSON key/value pair in PostgreSQL is an effective way to organize

In my dataset, I have a simple table with columns labeled Key_1, Key_2, and Value. Each row contains different combinations of Key_1 and Key_2 values. My goal is to transform the rows from this table into a JSON structure that looks like this: { "my ...

Develop a "Read More" button using Angular and JavaScript

I am in search of all tags with the class containtText. I want to retrieve those tags which have a value consisting of more than 300 characters and then use continue for the value. However, when I implement this code: <div class=" col-md-12 col-xl-12 c ...

The server's response is unpredictable, causing Json.Parse to fail intermittently

I have encountered a strange issue that is really frustrating. It all started when I noticed that my Json.Parse function failed intermittently. Here is the code snippet in question: const Info = JSON.parse(response); this.onInfoUpdate(Info.InfoConfig[0]); ...

Unable to consistently select a radio button via code across different browsers

Is there a way to automatically select a radio button based on the URL path? $(document).ready(function () { function checkRadioBasedOnUrl() { var urlPath = window.location.pathname.split("/"); console.log(urlPath); // ["", "tradeshow ...

Converts FlagName to a JSON format

Currently, I am tasked with converting values of type Distribution.PackageDescription.FlagName to a JSON object using the Text.JSON from the json package. My current approach looks like this: instance JSON FlagName where showJSON (FlagName n) = ma ...

What exactly does the statement if(item.some((item) => !item.available) represent in typescript?

Can you explain the meaning of if(item.some((item) => !item.available))? While looking at some code randomly, I came across this snippet: if(item.some((item) => !item.available){ } I'm curious about what it signifies. Can you elaborate on it? ...

Disappearing Into the Background Excluding Specific Divs

I have a dilemma with fading in and out a background image using jQuery fadeIn and fadeOut. The issue arises because my wrapper div contains elements such as sidebar and navigation that are positioned absolutely within the wrapper div, causing them to also ...

Stop ajax request when select2 is clicked

Is there a way to change the ajax call behavior in select2 drop down items so that it only retrieves data when I start typing in the search box, and not on click of the element? Your guidance on this issue would be highly appreciated. $("#ddlItems").sel ...

The lower section of the scrollbar is not visible

Whenever the vertical scroll bar appears on my website, the bottom half of it seems to be missing. For a live demonstration, you can visit the site HERE (navigate to the "FURTHER READING" tab). HTML: <!DOCTYPE html> <html lang="en"> <h ...

Open the JSON file and showcase its contents using Angular

I am attempting to read a JSON file and populate a table with the values. I've experimented with this.http.get('./data/file.json') .map(response => response.json()) .subscribe(result => this.results =result, function(error) ...

Transform legitimate JSON into a Task<string>

Currently, I am working on mocking ReadAsStringAsync on the first line to be used in a unit test that will result in a Task where the string represents the JSON provided below: var jsonString = await response.Content.ReadAsStringAsync(); // converting it ...

Place the token within the Nuxt auth-module

Working on a project using the Nuxt auth-module. The Login API response is structured like this: data:{ data:{ user:{ bio: null, createdAt: "2021-06-29T12:28:42.442Z", email: "<a href="/cdn- ...

Having trouble debugging a website remotely? Dealing with a JSON problem specifically in IE8

Currently, the website is functioning flawlessly on various machines except for those used by the client in Africa. Unfortunately, I have no way of accessing his specific machine due to geographical constraints. The client has limited IT knowledge, and we ...

Using destructuring assignment in a while loop is not functional

[a,b] = [b, a+b] is ineffective here as a and b are always set to 0 and 1. However, using a temporary variable to swap the values does work. function fibonacciSequence() { let [a, b, arr] = [0, 1, []] while (a <= 255) { arr.concat(a) [a, ...