Tips for efficiently finding and comparing text within the results generated by a for loop in Angular/Javascript

In my XML data, I have extracted all the tag names using a for loop and some other logic. Now, I am looking to find the word 'author' from the output values that are displayed in the console during the loop. If any of the output values match 'author', then I need to execute a specific condition. Here is the code snippet:

app.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'project';

  ngOnInit(): void {
    let xmldata = "<bookstore><book>" +
      "<title>Everyday Italian</title>" +
      "<author>Giada De Laurentiis</author>" +
      "<year>2005</year>" +
      "</book></bookstore>";
    var node = (new DOMParser()).parseFromString(xmldata, "text/xml").documentElement;
    var nodes = node.querySelectorAll("*");
    // console.log(nodes[4].tagName)
    for (var i = 0; i < nodes.length; i++) {
      var text = null;
      if (nodes[i].childNodes.length == 1 && nodes[i].childNodes[0].nodeType == 3) //if nodeType == text node
        text = nodes[i].textContent; //get text of the node
      //  console.log("TageName : ", nodes[i].tagName, ", Text : ", text);
      console.log(nodes[i].tagName)
    }
  }
}
   

Answer №1

We can convert the data output into an array, use the filter function to remove all authors, and then utilize map to extract only the inner texts.

Complete code snippet:

import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    <a target="_blank" href="https://angular.dev/overview">
      Learn more about Angular
    </a>
  `,
})
export class App {
  title = 'project';

  ngOnInit(): void {
    let xmldata =
      '<bookstore><book>' +
      '<title>Everyday Italian</title>' +
      '<author>Giada De Laurentiis</author>' +
      '<year>2005</year>' +
      '</book><book>' +
      '<title>Everyday Italian</title>' +
      '<author>Giada De Laurentiis1</author>' +
      '<year>2005</year>' +
      '</book><book>' +
      '<title>Everyday Italian</title>' +
      '<author>Giada De Laurentiis2</author>' +
      '<year>2005</year>' +
      '</book></bookstore>';
    var node = new DOMParser().parseFromString(
      xmldata,
      'text/xml'
    ).documentElement;
    var nodes = node.querySelectorAll('*');
    // converting nodes to an array, filtering out authors, and using map
    //to extract the necessary property for the output array!
    const requiredData = Array.prototype.slice
      .call(nodes, 0)
      .filter((x: any) => x.nodeName === 'author')
      .map((x: any) => x.textContent);
    console.log(requiredData);
  }
}

bootstrapApplication(App);

Check out the Stackblitz Demo

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

I would greatly appreciate your assistance in deciphering the JavaScript code provided in the book "Ajax in Action"

While reading through the Ajax in Action book, I came across a code snippet that has left me with a couple of questions. As someone who is new to web programming and still getting to grips with JavaScript, I am hoping for some clarity on the following: ...

What's the issue with conducting a unit test on a component that has dependencies with further dependencies?

I am experiencing an annoying error that seems to be my mistake and I cannot figure out how to resolve it. The issue lies within a simple component which serves as a top-bar element in my web application. This component has only one dependency, the UserSe ...

Angular component testing encountering undefined NgZone

I am facing a challenge while testing for bad input values in an Angular Date Range picker component that I am developing. In my ngOnInit() function, I include a check for minimum and maximum date values. However, when attempting to write a test case for ...

The Next.js website displays a favicon in Chrome, but it does not appear in Brave browser

As I work on my debut next.js website, I am configuring the favicon in index.js like this: <Head> <title>Create Next App</title> <link rel="icon" href="/favicon.ico" /> </Head> Initially, all my source ...

Issue: mongoose.model is not a valid function

I've been diving into several MEAN tutorials, and I've hit a snag that none of them seem to address. I keep encountering this error message: Uncaught TypeError: mongoose.model is not a function Even after removing node_modules and reinstalling ...

Executing an external Python script within a Vue application's terminal locally

Hello, I am new to using Vue.js and Firebase. Currently, I am working on creating a user interface for a network intrusion detection system with Vue.js. I have developed a Python script that allows me to send the terminal output to Firebase. Right now, I a ...

Caution in NEXTJS: Make sure the server HTML includes a corresponding <div> within a <div> tag

Struggling with a warning while rendering pages in my Next.js and MUI project. Here's the code, any insights on how to resolve this would be greatly appreciated! import "../styles/globals.scss"; import { AppProps } from "next/app"; ...

Node.js: Calculating the number of requests processed per second in the http.get()

In my node.js project, I am creating a simple application for sending HTTP requests. var http = require('http'); var options = { host: 'www.example.com', port: 80, path: '/index.html' }; for(var i = 0; i < 500; i++ ...

How to effectively handle null in Typescript when accessing types with index signatures unsafely

Why am I getting an error that test might be potentially undefined even though I've enabled strictNullCheck in my tsconfig.json file? (I'm unsure of the keys beforehand) const a: Record<string, {value: string}> = {} a["test"].va ...

How can you update an image's source when hovering over it?

My goal is to switch the image source upon mouseover using a combination of asp.net and javascript. Here is the code I am currently using: <asp:ImageButton id="button" runat="server" Height="65px" ImageUrl="~/images/logo.png" OnMouseOver="src='~ ...

AngularJS tree grid component with customizable cell templates

I have been utilizing the tree-grid component in AngularJS from this link: Here is an example of it on Plunker: http://plnkr.co/edit/CQwY0sNh3jcLLc0vMP5D?p=preview In comparison to ng-grid, I am unable to define cellTemplate, but I do require the abilit ...

What is the best way to filter two tables using only one search bar?

In my Vue2 application, I have implemented a pair of data tables on one of the pages. Each table is placed behind a tab, allowing users to choose which one they want to view. The search bar, however, is not confined within a tab as I wanted to avoid duplic ...

Tips for sending and retrieving parameters using the POST technique

Currently, I am in the process of building a user authentication form for my website using Javascript. I am utilizing Vue JS on the client-side and NodeJS with ExpressJS on the server-side. For the server-side functionality, I have implemented the followi ...

Unable to process form submission with AngularJS + Stormpath

I am facing an issue with form submission. Even though I believe that the login and password data are being sent correctly, nothing happens when I submit the form. I am attempting to submit the form without using ngSubmit because it is not feasible in my s ...

Leveraging React Native to position a view absolutely in the center of the screen without obstructing any other components

How can I center an image inside a view in the middle of the screen using position: "absolute"? The issue is that the view takes up 100% of the width and height of the screen, causing all components underneath it (such as input fields and buttons ...

Guide on toggling the visibility of two child components using *ngif in Angular 4 without losing the data

Is there a way to preserve data in my child component while using *ngIf to show and hide? I am unable to utilize the [hidden] attribute. <div id="parentcomponent"> <child1 *ngif="child1"></child1> <child2 *ngif="child2"></chi ...

Click on the navigation bar buttons to toggle between different divs and display multiple information boxes simultaneously

Here is the current code snippet... $("#contact").click(function() { if ( $( "#contact_div" ).length ) { $("#contact_div").remove(); } else { var html='<div id="contact_div" class="contact-info"><p>Contact info</p&g ...

retrieve data from an asynchronous request

Utilizing the AWS Service IotData within an AWS Lambda function requires the use of the AWS SDK. When constructing the IotData service, it is necessary to provide an IoT endpoint configuration parameter. To achieve this, another service is utilized to obta ...

What is the best way to conceal the HTML video controls for multiple videos displayed on a single webpage?

I have a web page that displays a collection of movies generated using a PHP foreach loop. The code snippet looks like this: foreach ($movies as $movie) { $pos = strrpos($movie, '/'); $id = $pos === false ? $movie : substr($movie, $pos ...

using javascript to access an opened html div

I am making an AJAX request in A.html and once the response is successful, I want to display a message in B.html. (The message should be displayed in a div with the id='mes_div' which is located in B.html.) How can I access B.html and how do I ac ...