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

Excessive geolocation position responses in Angular 5

I am trying to implement an Angular 5 component that will continuously fetch my current location every 3 seconds if it has changed. Here is a snippet of my code: export class WorkComponent implements OnInit { constructor(private userService: UserService ...

The Battle of node.js Modules: Comparing socket.io and express.static

The server.js file I am currently running is set up as follows: module.exports = server; var express = require('express'); var fs = require('fs'); var server = express.createServer(); var port = 58000; server.listen(port); var ...

Ways to confirm that the function handed over as a prop to a Vue component operates asynchronously

How can I determine if a prop Function is asynchronous? Consider the following prop in my component: callbackFunction: { type: Function, default: null, }, Is there a way to validate this and ensure that the provided Function i ...

Disabling a specific tab in an array of tabs using Angular and Typescript

Displayed below are 5 tabs that can be clicked by the user. My goal is to disable tabs 2 and 3, meaning that the tab names will still be visible but users will not be able to click on them. I attempted to set the tabs to active: false in the TypeScript fi ...

There seems to be a malfunction with the routing feature in the src/index.html file

My routing setup is not functioning as expected in src/index.html angular. What I have is a header with some links for navigation: <header> <div class="logo"> <div class="logo-img-div"> <img src="../../ass ...

Step-by-step guide on defining a context variable within a template

I am looking for a way to make my page dependent on a single model object emitted from an Observable. If it was a list, I would use <div ngFor="let currentListItem of myObservable | async" > However, since I only have one model and not a list, ngFo ...

Angular strictPropertyInitialization - best practices for initializing class members?

When initializing a component, I need to retrieve user information. However, with the Angular strict mode in place, I'm uncertain about where to fetch this data. I have considered 3 options. But which one is the most appropriate? Is there another alt ...

AngularJS - utilizing the directive $parsing to evaluate an expression and bind it to the scope object

I have set up my isolated directive to receive a string using the @ scope configuration. My goal is to convert this string into an object on the scope, so that I can manipulate its properties and values. Here's how it looks in HTML: <div directiv ...

Understanding the functionality of app.locals within app.get in an Express application and how to effectively parse data

I am currently developing a parse application using express. In my index file, I want to display different information to users based on whether they are logged in or not. However, I am facing an issue with storing the flag and logged-in user name using ap ...

Extracting textual information from Wikipedia through iframes?

Currently, I am working on a website project utilizing Squarespace. This site will feature multiple pages dedicated to individuals who have reached a level of notability worthy of having their own Wikipedia page. With over 150 pages planned, manually writi ...

Matching TypeScript search field names with column names

Seeking ways to create an API that allows admins to search for users in the database using various fields. // Define allowed search fields type SearchFieldType = 'name' | 'memberNo' | 'email' | 'companyName'; const ...

Guide to setting the first tab as the default tab using Thymeleaf, Css, and Bootstrap

I am currently working on a project where I need to dynamically create tabs based on a list retrieved from my Spring backend using Thymleaf and Bootstrap. While I have managed to successfully create the tabs and content, I am facing an issue where the fi ...

A guide on retrieving the upload status of a file using an AJAX post request

Is there a way to retrieve the status of uploaded files when the user cancels the process while uploading multiple files using an ajax call? This is how I am currently making the ajax request to upload files: var request = $.ajax({ url: 'file ...

Absence of property persists despite the use of null coalescing and optional chaining

Having some trouble with a piece of code that utilizes optional chaining and null coalescing. Despite this, I am confused as to why it is still flagging an error about the property not existing. See image below for more details: The error message display ...

Error message: "React Component not identified"

I am following [this React tutorial][1] and facing an issue right from the start as my React components are not being identified. Here is a snippet of my code: import React from 'react'; import {BrowserRouter as Router, Route, Routes} from "react ...

Issue with Chrome not triggering onMouseEnter event when an element blocking the cursor disappears in React

Important Note: This issue seems to be specific to Chrome Currently, React does not trigger the onMouseEnter event when a blocking element disappears. This behavior is different from standard JavaScript events and even delegated events. Below is a simpli ...

The resolvers contain the Query.Mutation but it is not specified in the schema

const { ApolloServer, gql } = require('apollo-server-express'); const express = require('express'); const port = process.env.PORT || 4000; const notes = [ { id: '1', content: 'This is a note', author: 'Adam ...

Updates made in MobX store are not displaying in the web browser

Why are the data changes not reflecting in the view after the api call? Here is the code snippet that might help: store.js import axios from 'axios'; import {encrypt, decrypt} from '../utils/pgp.js' import {observable, action, compute ...

Perform an Ajax call just one time

$('#addToCart').click(function () { let csrf = $("input[name=csrfmiddlewaretoken]").val(); let trTable = $(this).parents('div')[1]; let customPrice = $($(trTable).children('div') ...

Incorporate the block-input feature from sanity.io into your next.js blog for enhanced functionality

Currently, I'm in the process of creating a blog using next.js with sanity.io platform. However, I am facing some difficulties when it comes to utilizing the code-input plugin. What's working: I have successfully implemented the code component b ...