Analyzing an array of objects

Is there a way to filter an array of objects to only include elements that have 'text' containing 'ild'?

For example, consider the following array:

public data: any[] = [
  {
    treeViewKey:0,
    id: 1,
    text: 'Root Node 1'
  }, {
    treeViewKey:1,
    id: 2,
    text: 'Root Node 2'
  }, {
    treeViewKey:1_0,
    id: 3,
    parentId: 2,
    text: 'Child node of Root Node 2'
  }, {
    treeViewKey:1_1,
    id: 4,
    parentId: 2,
    text: 'Child node of Root Node 2'
  }, {
    treeViewKey:1_2_0,
    id: 5,
    parentId: 4,
    text: 'Child node of Root Node 2'
  }
];

I want to extract the elements where 'text' contains 'ild'. How can this be done efficiently using javascript or typescript?

The desired output would be:

[
    {
    treeViewKey:1_0,
    id: 3,
    parentId: 2,
    text: 'Child node of Root Node 2'
  }, {
    treeViewKey:1_1,
    id: 4,
    parentId: 2,
    text: 'Child node of Root Node 2'
  }, {
    treeViewKey:1_2_0,
    id: 5,
    parentId: 4,
    text: 'Child node of Root Node 2'
  }
]

Answer №1

If you seek to locate all the offspring, it is beneficial to focus on a specific attribute to retrieve them efficiently.

That attribute is known as the parentId. If the value of the parentId is mentioned, then those are considered as children nodes.

To sift through the input data effectively, search for entries with the parentId property specified.

Additionally, below is an example demonstrating how to find instances containing 'ild' in text, per your request:

const data = [
  {
    treeViewKey:0,
    id: 1,
    text: 'Root Node 1'
  }, 
  {
    treeViewKey:1,
    id: 2,
    text: 'Root Node 2'
  }, 
  {
    treeViewKey:'1_0',
    id: 3,
    parentId: 2,
    text: 'Child node of Root Node 2'
  }, {
    treeViewKey:'1_1',
    id: 4,
    parentId: 2,
    text: 'Child node of Root Node 2'
  }, {
    treeViewKey:'1_2_0',
    id: 5,
    parentId: 4,
    text: 'Child node of Root Node 2'
  }
];

// Filter elements based on parentId property
console.log(data.filter(el => el.parentId));
// Filter elements based on 'ild' string in text property
console.log(data.filter(el => el.text.includes('ild')));

Answer №2

For example:

const items = data.filter(item => item.parentId);

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

Using Angular 2 HTTP to retrieve a list of file names from a Node backend directory

I am currently attempting to establish a connection between an Angular 2 frontend and a Node/Express backend using an HTTP GET request. The backend should respond by providing a list of file names from a specific folder using the fs.readdir method. I have ...

Delivery person receiving biscuit but my internet browser doesn't seem to be getting it when I attempt to retrieve it

Currently, I am in the process of creating a website using Flask and React. The user is required to input an email and password on a form, which is then sent via axios.post to the backend. The backend checks if the email and password match with the databas ...

Contrast between the $q constructor and promise interface

Can you explain the concept of a promise interface in angular JS? Furthermore, what exactly is a $q constructor? In which scenarios are these functionalities utilized and how do they differ from each other? I have looked into multiple resources but st ...

What is the maximum number of JavaScript functions allowed in a single HTML file?

My HTML5 file includes JavaScript (created from CoffeeScript) directly within the HTML file, as I prefer this approach for my HTML/JavaScript programming. The code consists of four JavaScript functions that convert one temperature unit to another. Strang ...

`How can I develop a function in Angular 6 that extracts query parameters from the URL?`

I have here the following code. Can anyone suggest an alternative or more efficient method for retrieving the queryParams from the url? fetchSolutionId(){ let solutionId: number; this.activatedRoute.queryParams.subscribe((queryParams) => { ...

What is the functionality of the arguments in the ajax function?

I'm currently following a tutorial that includes the code below: https://i.sstatic.net/a68AO.png However, I'm confused about the purpose of url, cache, and success. Are they arrays? How do they function? ...

Transform JSON reply in JavaScript/Typescript/Angular

Looking for assistance with restructuring JSON data received from a server API for easier processing. You can find the input JSON file at assets/input-json.json within the stackblitz project: https://stackblitz.com/edit/angular-ivy-87qser?file=src/assets/ ...

Determining the correct type for a recursive function

I have created a function that is capable of recursively traversing through a nested or non-nested object to search for a specific key and extract its value. const findName = <T extends object>(obj: T, keyToFind: string): T[] => { return Object ...

Navigate through the DOM to return an image

I have a question about clicking on the image '.escape' and passing back the source of the image '.myimg2' when clicked. Here is my attempt at accomplishing this task: I understand that it involves traversing the DOM, but I am not very ...

What is the best way to format specific text as bold within an input text field?

I am attempting to make certain text bold within an input text field. However, I'm uncertain about how to achieve this because HTML code is not recognized inside a text field. Therefore, using <b> will not be effective. Is there a way to bold sp ...

Vue app hosted on Firebase displays a blank page when user logs in

After deploying my Vue2 project to Firebase hosting server, visitors are required to log in to access the other pages. The issue is that once a user successfully logs in, they are redirected to the next page but it appears blank. Below is what the firebas ...

Tips on updating pinned row information in AG Grid Vue

I have a specific row pinned to the bottom in the grid. Whenever I add or remove some rowData in the grid, I need to update that pinned row. Take a look at the code snippet below: this.gridApi.pinnedBottomRowData = rowNode.setDataValue(date, dataToPush); t ...

Adding jQuery namespace to AngularJS

I'm facing a bit of an issue here. I've implemented RequireJS to manage my modules and dependencies. To prevent cluttering the global namespace, I've set up the following configuration to avoid declaring $ or jQuery globally: require.confi ...

Error: Supabase and Next.js encountered a self-signed certificate within the certificate chain causing an AuthRetryableFetchError

Encountering an error related to certificates while attempting to retrieve the user from Supabase within getServerSideProps using Next.js: AuthRetryableFetchError: request to https://[redacted].supabase.co/auth/v1/user failed, reason: self signed certifica ...

What could be causing the form body to return null in a PUT request?

What could be causing the form data to not be stored in req.body? EJS/HTML <form onsubmit="EditJob()" class="editForm"> <div class="form-group-edit"> <label for="position">Position</label> <input type="pos ...

Prevent the sender from receiving notifications from Firestore

Data is transmitted to firestore by the sender firestore saves the data firestore shares the data with all connected clients, sender included Is there a method for the sender to not receive the notification? OR If the sender does get the notification, is ...

The art of finding information algorithm

Having a JSON file containing about 10,000 records, each record includes a timestamp in the format '2011-04-29'. Currently, I also have a client-side array (referred to as our calendar) with arrays such as - ['2011-04-26', '2011- ...

How to stop the HTTP Basic Auth popup with AngularJS Interceptors

In the process of developing a web app using AngularJS (1.2.16) with a RESTful API, I encountered an issue where I wanted to send 401 Unauthorized responses for requests with invalid or missing authentication information. Despite having an HTTP interceptor ...

"JavaScript's versatility shines through with its ability to handle multiple variables

Presently, I am working with the following script: <v-tab :title="siteObject.xip_infos[index].lineid" > <div class="description text-left" :class="{ 'text-danger': item.status === 'DEACTIVE' }"> <small v-for="(f ...

Issue with adding object to array using forEach() function

As I navigate my way through an express route, I am puzzled as to why the "purchasedCards" array turns out empty after going through these database calls. Despite successfully gathering all the necessary information from various DB Queries and placing it i ...