Find a string that matches an element in a list

I currently have a list structured like this

let array = [
     { url: 'url1'},
     { url: 'url2/test', children: [{url: 'url2/test/test'}, {url: 'url2/test2/test'}],
     { url: 'url3', children: [{url: 'url3/test3/test3}, {url: 'url3/test3/test1'}],  children: [{url: 'url3/test3/test1/test5'}]},
     { url: 'url4', children: [{url: 'url4/test4/test4'}, {url: 'url: 'url4/test4/test4'}]]

and there is also an input string that represents a URL (e.g url: 'url3/test3/test1').

My goal is to verify if the input URL exists in the list without resorting to the usage of a for loop. (perhaps using map, some, filter or other functions..)

Can anyone provide guidance on how I can accomplish this task?

I am trying to determine if the

Answer №1

To implement a recursive function called check, start by checking if the object has a children property. If it does, call the some method to get the desired result.

let array = [{url:'url1'},{url:'url2/test',children:[{url:'url2/test/test'},{url:'url2/test2/test'}]},{url:'url3',children:[{url:'url3/test3/test3'},{url:'url3/test3/test1'}],},{url:'url4',children:[{url:'url4/test4/test4'},{url:'url3/test4/test4'}]}];

function check(arr, url) {
  return arr.some(a => a.url == url || (a.children && check(a.children, url)));
}

let isExists = check(array, 'url3/test3/test3');
console.log(isExists);

let isExists2 = check(array, 'url3/test3');
console.log(isExists2);

Answer №2

Give this a shot:

var searchTerm = "url3/test/test1";
var position = array.indexOf(array.find(element1 => {
if (element1.children !== undefined) return element1.children.some(element2 => element2.url.includes(searchTerm));
}));

Also, make sure to tidy up the array as it's currently a bit chaotic. Here's the updated snippet:

let array = [
     { url: 'url1'},
     { url: 'url2/test', children: [{url: 'url2/test/test'}, {url: 'url2/test2/test'}]},
     { url: 'url3', children: [{url: 'url3/test3/test3'}, {url: 'url3/test3/test1'}, {url: 'url3/test3/test1/test5'}]},
     { url: 'url4', children: [{url: 'url4/test4/test4'}, {url: 'url3/test4/test4'}]}]
     
function searchForItem(searchTerm) {
var position = array.indexOf(array.find(element1 => {
if (element1.children !== undefined) return element1.children.some(element2 => element2.url.includes(searchTerm));
}));
if (position > -1) console.log(array[position].url); else console.log("Could not find " + searchTerm)
}
<input oninput="searchForItem(this.value)">

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

Following a successful compilation, the Angular application displays an empty page

Alert: Uncaught TypeError: Cannot read property 'length' of undefined at Object./src/components/Carousel.vue (Carousel.vue:123) at __webpack_require__ (bootstrap:1024) at Module../src/main.js (main.js:1) at __webpack_require__ (b ...

How can I place an icon on a specific location in a Highcharts map?

I am currently utilizing Highcharts to showcase maps within my application. I am aiming to achieve two specific functionalities: 1) Upon clicking on any area, I want that area to be highlighted in red {completed} 2) Upon clicking on any area, I intend f ...

Obtaining the component instance ('this') from a template

Imagine we are in a situation where we need to connect a child component property to the component instance itself within a template: <child-component parent="???"></child-component1> Is there a solution for this without having to create a sp ...

Adding a custom source to the script tag in Angular 7

I am currently using angular cli to develop my web application. The app is being built in the dist folder as of now. This is the index.html file: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Adm ...

I am encountering a problem with my Material UI react-swipeable-views while using TypeScript

It seems that there is a mismatch in the version of some components. import * as React from "react"; import { useTheme } from "@mui/material/styles"; import Box from "@mui/material/Box"; import MobileStepper from "@mui/ma ...

Conceal the Froala editor when blur events occur

Currently, I am utilizing Forala with the specific setting: initOnClick: true, Everything is running smoothly, but is there a way to accomplish the "opposite" I'm looking to hide the editor upon blur? I have searched through the documentation, but d ...

Modifying data within nested objects using Typescript

Imagine having an object like this: { b954WYBCC4YbsMM36trawb00xZ32: { activity1: "pending", activity2: "pending" }, ​ pby0CAqQ1hTlagIqBTQf6l2Ti9L2: { activity1: "pending", activity2: "pending" } } with the in ...

Customize the height of individual carousel items in Primeng carousel

Hey there, I'm currently using the primeng carousel component and running into an issue where the carousel height is always based on the tallest item. I am looking to have an automatic height for each individual carousel item instead. Do you think th ...

What causes Gun.js to generate duplicate messages within a ReactJs environment?

I need assistance with my React application where gun.js is implemented. The issue I am facing is that messages are being duplicated on every render and update. Can someone please review my code and help me figure out what's wrong? Here is the code s ...

Pagination problem arises when sorting through items

I am facing an issue with filtering items on different pages of my React website. The problem I encounter is that the filtering functionality only works on the initial page where the data is loaded. Code: CustomersEpolicyPage.tsx import React, {useEffect ...

How to Retrieve Grandparent Component Attributes in Angular Using Grandchild Components

I am constructing an Angular application and facing the challenge of accessing a property of Component 1 within Component 3. In this scenario, the relationship is described as grandparent-grandchild. Successfully establishing communication between parent/ ...

Tips for testing an Angular Service that utilizes AngularFireDatabase by utilizing Jasmine Spy/Mock

I am currently testing my data service, and while I can successfully test it using real services like AngularFireDatabase, I am facing issues with getting the mocked version to work for testing purposes. The DataStorage class in use is designed to combine ...

Unable to generate paths in Ionic 3

I am trying to view the actual route on the URL, but I'm having trouble figuring out exactly what needs to be changed. I've been referring to the documentation at: https://ionicframework.com/docs/api/navigation/IonicPage/ However, I keep encoun ...

Leverage a provider implementation within another implementation of the same provider in Angular

Is it possible to inject one provider implementation into another implementation of the same provider in Angular? I have been unable to achieve this so far. The goal is to be able to customize the second implementation using data from the first implementat ...

One system hosting two distinct projects, each running on its own unique node version

Managing two different projects with distinct dependencies has become a challenge for me. One project relies on AngularJS and node v4.2.0, while the other is built on Angular 6 requiring node v8.11.3. During development, I utilize nvm for windows to switc ...

Component coding in Angular 2 allows for seamless integration and customization of Material

I am looking to initiate the start.toggle() function (associated with Angular 2 material md-sidenav-layout component) when the test() method is triggered. How can I execute md-sidenav-layout's start.toggle() in the app.component.ts file? app.componen ...

What is the best way to simulate DOCUMENT dependency injection for unit tests using Jest?

Currently, I have integrated a component known as 'A' which relies on the document object for its functionality. The component features a method called onClose(), which utilizes the document object service to retrieve elements using querySelector ...

Capturing the httpClient response within a service using rxjs

My application has a LoginComponent which includes a form for user credentials, and a LoginService responsible for making API calls using an httpClient. In my services, I usually return the call so that I can subscribe to it within my component as needed. ...

Typescript is failing to infer the definition of an object, even after conducting a thorough check

I am encountering an issue with the code structure below: interface Data { isAvailable: boolean; } const foo = (data: Data | undefined, error: boolean) => { const hasError = error || !data; if (!hasError) { if (data.isAvailable) // do so ...

What are the distinctions in type-narrowing when assigning values using ternary expressions versus if-else statements?

It seems that the type checker is handling the typing of m in print() differently based on whether m was assigned through a ternary expression or an if-else statement. What sets apart the first line in the print() function from the commented code below it? ...