What is the best way to flatten a nested array containing various objects, while extracting values based on the existing property names?

I am seeking a way to flatten a nested array containing different objects and retrieve only the existing values from specific property names within those objects.

Specifically, I am interested in extracting all the propertyId values from a nested array consisting of two distinct object types.

export interface LeftMenuItem {
    text: string;
    routerUrl?: string;
    isExpanded: boolean;  
    propertyId?: string;
    children: LeftMenuChildrenItem[];
}
export interface LeftMenuChildrenItem {
    text: string;
    routerUrl?. string;
    propertyId?: string;
    isCustomer: boolean
}

const leftMenuPropertyIds: string[] = [];

this.leftMenuItems.forEach(val1 => {
    if (val1.propertyId) {
        leftMenuPropertyIds.push(val1.propertyId);
    }
    if (val1.children.length > 0) {
        val1.children.forEach(val2 => {
            if (val2.propertyId) {
                leftMenuPropertyIds.push(val2.propertyId);
            }
        });
    }
});

console.log(leftMenuPropertyIds);

Answer №1

Use the reduce method to flatten both an array and an object, effectively removing unnecessary nodes.

const items = [
  {
    id: "1",
    name: "Sample item 1",
    children: [
      { id: "2", name: "Child item 1", children: [] },
      { id: "", name: "Child item 2", children: [] },
      { id: "3", name: "Child item 3", children: [] }
    ]
  }
];

const flatten = (node, result) => {
  if (node.id) result.push(node.id);
  (node.children || []).forEach(child => flatten(child, result));
  return result;
};
const flattenedList = items.reduce((resultArray, currentItem) => flatten(currentItem, resultArray), []);

console.log(flattenedList);

Answer №2

To address compatibility concerns, you have the option to utilize methods such as filter(), map(), and flatMap() on an array. Afterwards, employ ... to spread out the outcomes into a unified array.

function getLeftMenuPropertyIds(): string[] {
  const leftMenuIds = this.leftMenuItems
    .filter(leftMenuItem => leftMenuItem.propertyId !== undefined)
    .map(letMenuItem => letMenuItem.propertyId);

  const leftMenuChildrenIds = this.leftMenuItems
    .flatMap(leftMenuItem => leftMenuItem.children)
    .filter(child => child.propertyId !== undefined)
    .map(child => child.propertyId);

  return [...leftMenuChildrenIds, ...leftMenuIds]
}

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

Error in Django & Angular 2: {_dataService is not defined}

I recently tried incorporating Angular 2 into my Django application as a frontend. However, I encountered an issue while attempting to create a GET request. Angular 2 kept throwing me an error that I couldn't paste here due to formatting constraints. ...

Angular - Ensuring service completion before proceeding with navigation

I'm currently facing an issue where I need to populate data in a service before navigating, but the navigation is happening before the data is ready. Here's the code in my service: addToken(token) { this.cookieService.set( 'token', ...

Using JavaScript to organize and categorize data within an array

I am working with a multidimensional array and need to filter it based on the value at a specific index position. Here is what the array looks like: arr = [ [1 , 101 , 'New post ', 0], [2, 101 , 'New Post' , 1], ...

Is it possible to render a Numpy array immutable?

This reference presents a method to enforce immutability in a Numpy array by using the line of code .flags.writeable = False However, upon testing this with the following code snippet: arr = np.arange(20).reshape((4,5)) arr.flags.writeable = False arr f ...

Can anyone provide examples of how RegisterClientScriptBlock parameters are used in practical situations?

https://i.sstatic.net/dVjHt.jpg I've always struggled to grasp the true purpose of using the Control, Type, and Key in this particular class. Typically, I would use it with: this, GetType(), "xx" however, now I am determined to gain a deeper unders ...

Implementing jQuery UI toggleClass method to seamlessly alternate between two distinct CSS classes

My goal is to toggle between two CSS classes on a selector click using Jquery UI .toggleClass(), but unfortunately, it's not producing the desired toggle effect. $(".toggle").click(function () { $(".archivePosts .columns").removeClass( "l ...

Unable to retrieve the current status of Li from the backend code

I have created a code snippet to load controls on different tabs by using li elements with the attribute runat=server. However, I am facing an issue where I need to load controls based on the active li tab. How can I determine which tab was clicked from t ...

Retrieve PDF from Controller using jQuery AJAX request

While searching for solutions on how to create a PDF using a controller in EvoPDF, I noticed that none of the examples addressed the scenario where the controller is called via jQuery AJAX. In my application, I have a simple jQuery function that sends dat ...

Issue with AngularJs NgRoute

Encountering an issue with ngRoute on angularjs, version 1.6.9. Developed a simple route like "/test/:yourname" where "yourname" serves as a variable, however facing the following challenges: 1) Visiting the address "http://localhost:8080/test/rafael" re ...

What could be the reason behind the disappearance of text from the previously highlighted button in my calculator's "button grid" when I change the highlighted button?

Currently, I am in the midst of creating a tip calculator with a grid consisting of various percentage buttons. My main objective is to change the font and background color when any tip button is selected. Nevertheless, an issue has surfaced - whenever I h ...

Initiating the "cellValueChanged" event within the bespoke renderer component of Angular AG Grid when the selection is changed

How can I trigger the "cellValueChanged" event in an Angular AG Grid custom renderer component when a select element is changed? I have been working with Angular AG Grid and a custom renderer component. My goal is to fire the (cellValueChanged)="onCellValu ...

Include a class in the declaration file (*d.ts)

I am trying to enhance the Express Session typings to incorporate my custom data in session storage. In my code, I have an object req.session.user which is an instance of a class called User: export class User { public login: string; public hashed ...

Efficient ways to manage dropdown cells in ReactGrid

Is there a way to assign individual values to each select element in a cell? I am using ReactGrid with react version 16 There seems to be an issue with the onchange function, and I'm struggling to find help import * as React from "react"; ...

Best Practices for TypeScript and React: How to Handle Component State for Mounted Components

One technique to avoid calling .setState() on an unmounted component is by using a private property like _isMounted to keep track of it, as discussed in a blog post. I have implemented this method as follows: class Hello extends React.PureComponent{ _isM ...

Troubleshooting NodeJS with Socket.IO 1.0: Identifying Memory Leaks Beyond the Heap

We have encountered an issue while trying to deploy a small NodeJS app with Socket.IO. The problem arises when the total memory usage (rss) exceeds 2gb after approximately 2 hours, despite the heap size being within acceptable limits. To confirm that the ...

Properly implementing prototypal inheritance: best practices

While there are numerous discussions on prototypal inheritance in JavaScript already, I assure you this is not just another lazy copy. Having thoroughly read all existing threads, I've noticed a plethora of syntactic approaches and varying answers whi ...

When trying to upload numerous files, only a single file ends up being

The issue is with the function that is only uploading 1 file instead of all 6 files. It seems to be returning an array $fileDirectories with a dimension of 1, whereas I expected it to have 6 dimensions. The interesting thing is that count($_FILES['fil ...

JavaScript effectively divides multiple child dropdowns with the main dropdown, thanks to Bootstrap innovation

I have implemented a jQuery function to dynamically change multiple child dropdowns based on the selected value of the main dropdown. For reference, you can view the image here. However, I encountered an issue when applying the Bootstrap styles "form-con ...

Having trouble setting $scope after redirecting to a partial template via routing

Looking to create a website that loads all necessary templates upon the initial visit. Currently, I only have one partial template but plan to add more in the future. Despite having just this one template, I'm struggling with binding the data from my ...

no output upon completion of a class constructor - JavaScript

I am facing a perplexing issue with my code. Let me break it down for you: class Block{ constructor(timeStamp, lastBlockHash, thisBlockData, thisBlockHash){ this.timeStamp = timeStamp; this.lastBlockHash = lastBlockHash; this.t ...