A guide on showcasing nested arrays data in an Angular application

info = [
    {
        list: [
            { title: 'apple'}
        ]
    },
    {
        list: [
            { title: 'banana'}
        ]
    }
]

My goal here is to extract the list items. Here is how they are structured.

desired result:

info = [
    {
        title: 'apple'
    },
    {
        title: 'banana'
    }
];

This will eliminate the empty array and consolidate the data accordingly.

Answer №1

Method 1:

To simplify your array, you can utilize the reduce method like so -

var data = [
    {
        rows: [
            { name: 'a'}
        ]
    },
    {
        rows: [
            { name: 'b'}
        ]
    },
    {
        rows: []
    }
]

var reducedSet = [];
data.reduce((accumulator, currentValue, currentIndex) => {
  var currentRows = currentValue.rows;
  var rowLength = currentRows && currentRows.length
  if (rowLength) {
    for (i = 0; i < rowLength; i++) {
            accumulator.push(currentRows[i]);
        }
    return accumulator;
  }
}, reducedSet);

console.log(reducedSet);

Method 2:

Alternatively, you can approach it in this way too -

var data = [
    {
        rows: [
            { name: 'a'}
        ]
    },
    {
        rows: [
            { name: 'b'}
        ]
    },
    {
        rows: []
    }
];

var result = data.filter(f => f.rows && f.rows.length && f.rows.length > 0).map((currentValue) => {
  return currentValue.rows;
}).flat();

console.log(result);

The code above filters out empty rows first, maps the data, and flattens the final result.

Answer №2

data = [
    {
        rows: [
            { name: 'a'},
        ]
    },
    {
        rows: [
            { name: 'b'},
        ]
    },
    {
        rows: []
    }
]

let transformedData = data.map(item => {
    return item.rows.map(innerItem => {
        return {
            name: innerItem.name
        }
    })
 })

transformedData = transformedData.flat()

console.log(transformedData)

You can give this a try, it seems to achieve the desired outcome based on my observations.

Answer №3

If you're looking for a solution, this code snippet may be of help. It is designed to handle scenarios where there are multiple occurrences of the name element within a single rows.

let data = [] // YOUR OBJECT IN THE QUESTION

    let data2: any = []
    data.forEach(el => {
    if(el.rows.length > 0) {
    data2 = [...data2, ...el.rows];
       
        }
})


console.log('data2', data2);

Answer №4

If you're looking to streamline it using the latest JavaScript techniques, this is how it's done.

const rearrangeData = (dataToTransform) => dataToTransform.reduce((transformedData, { rows }) => transformedData.concat(rows), []);

In essence, a fresh array is created and then for each item in the initial data set, the content of the rows property is extracted and added to the array.

Answer №5

data.filter(item => {
  return item.rows !== [];
});

A filtering operation can be applied to the array.

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

Always directing to the initial page upon refreshing the browser in Angular's secondary route

In my app, there is a default component called StartComponent, accessed through the Angular router's start route. Therefore, in the browser address bar, it appears as myhost/start. Upon navigating to the second route, the app logic takes me to Second ...

Input for uncomplicated changing identifier

I am looking to create types for dynamic keys that will be of type number. I have two similar types defined as follows: type UseCalculatePayments = () => { totalPayments: number; aggregate: number; condition: boolean; }; type UseCalculateCommissio ...

React Full Calendar Error: Unable to access property 'calendar' from undefined

I'm encountering an issue while attempting to save selected time information in state. Any assistance would be greatly appreciated, thank you for your help! Please feel free to ask if more specific details are required. Below is a snippet of code fro ...

File handling in Angular 2 using Typescript involves understanding the fundamental syntax for managing files

Would someone be able to explain the fundamental syntax for reading and writing text files, also known as file handling in TypeScript? If there is a corresponding link that anyone could provide, it would be greatly appreciated. ...

ways to instantly showcase the input's value within a DIV element

For example, I have a div with the ID of "someDiv" and an input text field with the ID of "someInput". How can I make it so that the value entered into the input field displays in the DIV in real time? For instance, if I type the letter "a" in the input fi ...

Using a JSON string with form field names and corresponding values to automatically fill in form fields using jQuery

My JSON string looks like this: [{"meta_key":"algemeen_reden","meta_value":"oplevering"},{"meta_key":"algemeen_netspanning","meta_value":"230"}] Currently, I am using the following script to fill out form fields: // Grab Algemeen Data get_algemeen_data ...

find your way to an angular component within a different module

Currently, I am utilizing this template and running into an issue with navigating from the login component to a different component associated with another module. I have attempted using both this.router.navigate(['myRoute']) and this.router.nav ...

Identifying the scenario where Partial<T> inherits from T

I am facing a scenario where I am working towards achieving a specific "state": type State = { foo: number, bar: number, baz?: string }; Initially, I may not have reached the complete State yet but rather align with the structure of Partial<State>. ...

Developing a JSONP functionality

I am currently trying to use JSONP in order to display data within my div. However, the code is not showing anything. I have also included jquery.jsonp.js in my project with the following path: PRJFOLDER->WEBPages->JavaScript->qu ...

Adding Roles Using Discord.js - A Simple Guide

I'm currently working on a Discord bot using Discord.js, and I am trying to implement a feature where users can use a command to assign themselves a role. However, despite my best efforts, I am unable to get this functionality to work. In my bot' ...

Create a series of canvas lines connecting all divs that share a common class identifier

Currently, I am in the process of creating a document that will establish a tree-type graph based on user input. My goal is to link styled divs with canvas lines to show their connection to the parent div. I have been utilizing .getBoundingClientRect() to ...

Failing to hide a div on hover: Hoverintent's shortcomings

When I hover over the div with the unique identifier id="navbar", it doesn't seem to trigger any actions. I have included the following script in my document head: <script type="text/javascript" src="https://ajax.googleapi ...

We could not locate the requested resource with a DELETE request using the fetch JSON method

Currently, I am in the process of developing a webpage that utilizes JSON API REST alongside XAMPP with an Apache server. Up until now, everything has been working smoothly as I have been utilizing the DELETE method successfully. However, I seem to have hi ...

Can a string be transformed into HTTP POST parameters?

Below is a snippet of code where I've utilized the .serialize() method to convert all form inputs into a string, which is then sent to the server: $.ajax({ type: "post", url: wp_urls.ajax_url, data: { action: "submit_form", ...

Is it possible to incorporate a fadein animation into a function?

Developing the entire HTML structure using JavaScript is one of my skills. Here is a snippet as an example: function generateHeader () { $('body').append( $('<header>') .attr('id', "main-header") ...

Checking whether a node stream operates in objectMode

When working with a node js stream object, how can I ascertain if it is an object stream in objectMode? For example, suppose I have a readable stream instance: const myReadableStream = new ReadableStreamImplementation({ options: { objectMode : true } ...

Utilizing NPM Workspace Project in conjunction with Vite to eliminate the necessity of the dist folder during the Vite build process

I am currently working on a project that involves a module using full path exports instead of index files. This project is divided into 2 NPM workspaces: one called core and the other called examples. The challenge I am facing is avoiding long import pat ...

Sign up for a Jquery template event

When utilizing a jquery template, the following HTML markup is being used: <div id="results"> <div class="CommentItem" commentid="33064" id="33064" data-guid="/Profile/Profile.aspx?id=Charliedog33"> <div class="CommentPic" ...

Difficulty sending a parameter to the onClick function of a React Button

I'm struggling with passing parameters to my callback function when clicking a material-ui button. Unfortunately, the following approach is not yielding the expected results. const fetchData = async (param) => { } <Button onClick={fetchData(&a ...

Error: Could not locate module: 'path' in ' ode_modulessource-map-support' - npm

During the migration process from Angular 5 to Angular 7, I encountered a couple of errors such as map and forkJoin being deprecated. Thankfully, those issues were resolved. However, there is still one lingering error that crops up when running ng serve. ...