I am on a quest to locate a specific key within an array of objects and then validate it using Regex

I've been struggling with this for over 3 days and still haven't found a solution. It feels like trying to find a needle in a haystack, but I'm determined to figure it out.

My goal is to search for a specific key in an array of objects and if it contains (a) or (b), I want to set another key to true.

Unfortunately, I seem to be making a mistake somewhere in my code, but I can't pinpoint where.

Here is the current state of my code:

let reg = /\((.+?)\)/;
let aggregatedArray: Array<any> = [];
const allWeeksDescription = this.selectedPlan.weeklyOffer;
console.log(allWeeksDescription);
let prop = 'description';
for (prop in allWeeksDescription) {
    allWeeksDescription[prop].forEach(function(k:any) {
          aggregatedArray.push(k.description);
          console.log(aggregatedArray);
     })
}

Despite receiving a successful log in the console, I also encounter this error:

ORIGINAL EXCEPTION: allWeeksDescription[prop].forEach is not a function

My main objective is to find the key ('description') and if its value matches the RegEx, then set another key ('exists') to true. If there's no match, the value should remain as false. The RegEx pattern is stored in this variable:

let reg = /\((.+?)\)/;

When I check the console, the output looks something like this:

{
   monday: [
         {
            description: "(a)",
            exists: false
         },
         ...
        ]
tuesday:  [
         {
            description: "test",
            exists: false
         },
         ...
        ]
     }

To sum it up, I need to iterate through the description keys, match them with the Regex, and update the corresponding exists key based on the match result. Your assistance with this problem would be greatly appreciated as I've spent too much time on it already.

Thank you in advance.

Answer №1

One way to iterate through an anonymous type object using a foreach loop is by extracting all keys of the object and making sure they conform to a specific pattern. Here's an example:

let regex = /\((.+?)\)/;
let arrayOfMatches = [];
const weeklyOfferDescriptions = this.selectedPlan.weeklyOffer;
console.log(weeklyOfferDescriptions);
let property = 'description';
Object.keys(weeklyOfferDescriptions).forEach(function(key) {
    regex.match(weeklyOfferDescriptions[key]) && aggregatedArray.push(key.description);
    console.log(arrayOfMatches);
})

Answer №2

If the specific object referred to as allWeeksDescription is the subject of your explanation at the end of your message, then it is essential to modify your for loop as follows:

  let matchingDays = []; // for keeping track of days that match
  for(let dayLabel in allWeeksDescription) {
      /* Represents one day (= an array) in the initial object */
      let day = allWeeksDescription[dayLabel];
      /* Iterating through all items in the array */
      day.forEach( d => {
        /* `d` denotes one element of the array */

        /* Check if it meets the criteria of your regex */
        if(d.description.search(reg) !== -1) {
          /* Implement actions as needed, as the description matches your regex */
          d.exists = true;
          matchingDays.push(day);
        }
      });
    }

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

Caution: It is important that each child within a list is assigned a distinct "key" prop - specifically in the Tbody component

I encountered the error above while running jest tests on a component. npm start is running without any issues. The component code is as follows: .... .... const [Data, setData] = useState([]); useEffect(() => { const fetchData = async () =&g ...

Using Typescript to Convert JSON Data into Object Instances

My challenge involves a Json object structure that looks something like this: { "key" : "false", "key2" : "1.00", "key3" : "value" } I am seeking to convert this in Typescript to achieve th ...

Struggling to incorporate infinite scroll feature into JSON script that is already functioning smoothly

After developing a phonegap application, I created a page called photos.html to fetch photos from my server using JSON. However, despite successfully retrieving all the photos stored in my MySQL database on the server with JSON, I struggled to integrate In ...

Obtaining only a portion of the text when copying and editing it

I have a React application where I am attempting to copy text from an HTML element, modify it, and then send it back to the user. I have been successful in achieving this, but I am facing an issue where even if I select only a portion of the text, I still ...

jQuery AJAX chained together using promises

In my current project, I am facing an issue where I have 4 get requests being fired simultaneously. Due to using fade effects and the asynchronous nature of these requests, there are times when empty data is received intermittently. To address this issue, ...

What is the best way to store JSON data in Mongoose database?

I have some json data that I need to store in a mongoose database, but I'm struggling with how to structure my mongoose schema. data: { 'posts[0][commentId]': '0', 'posts[0][id]': '1', 'posts[0][post ...

Interacting with a Web API using JavaScript following successful authentication with Azure AD B2C

Currently, I am working on a .Net Web App. After going through the authentication process with Azure AD B2C using the Azure AD Connect protocol, my app's controller successfully obtains an access token via the MSAL library (written in C# code) to conn ...

Angular's getter value triggers the ExpressionChangedAfterItHasBeenCheckedError

I'm encountering the ExpressionChangedAfterItHasBeenCheckedError due to my getter function, selectedRows, in my component. public get selectedRows() { if (this.gridApi) { return this.gridApi.getSelectedRows(); } else { return null; } } ...

Troubleshooting: JavaScript code not functioning properly with variable input instead of fixed value

I have encountered an issue with a JS function that I'm using. The function is shown below: // A simple array where we keep track of things that are filed. filed = []; function fileIt(thing) { // Dynamically call the file method of whatever ' ...

Updating a list with new values and converting it into a JSON object before transmission

var jsonElements = List[String]() val params = Map("host"->host) for((key,value)<-mapSql){ val map = Map("metric"->key,"timestamp"->new Date().getTime,"value"->value,"tags"->params) jsonElements=JsonUtility.toJSONStri ...

JavaScript code to dynamically change the minimum value of an input field when the page

How can I use JavaScript to change the minimum value onload? I tried the following code but it didn't work: <script type="text/javascript">$(document).ready(function(){ $("#quantity_5c27c535d66fc").min('10'); });</script> ...

Encountering a sudden problem while running gulp build due to a node_module - Surprising occurrence of Unexpected

Encountering an unexpected issue while running a gulp build process for a web app that I am struggling to resolve. The problem did not exist on the evening of 25/01/2019, but when attempting to execute the gulp build process this morning (30/01/2019), an ...

Ways to prevent the Layout component from rendering on the NextJS login page

Is there a way to prevent the rendering of the Layout component in NextJS when the route is /login, /register, etc? const MyApp = ({ Component, pageProps }) => { return ( <Layout> <Component {...pageProps} /> </Layout> ...

I am having difficulty aligning the vertical touch event owl carousel

Here is the link: "jsfiddle.net/nLJ79/". Can you try to find a solution to make the owl carousel vertical? ...

Angular 2, the change event is not triggering when a bootstrap checkbox is clicked

Encountering an issue, the (change) function is not triggering in a specific checkbox. <input [(ngModel)]="driver.glasses" name="glasses" type="checkbox" class="make-switch" (change)="changeFunction()" data-on-color="primary" data-off-color="info"&g ...

An advanced password checker that notifies the user of any spaces in their password

I need help fixing my JavaScript code. The program should prompt the user for a password using a dialogue box, and then validate that the input has no spaces. If a space is detected, the program should stop and display an alert saying "Invalid, contains a ...

What is the reason for sending a single file to the server?

A function called "import File" was developed to send multiple files to the server, but only one file is being received. Input: <input type="files" id="files" name="files" multiple onChange={ (e) => this.importFile(e.target.files) } ...

Objective-C and the World of WebSockets

Possible Duplicates: Comparison of WebSockets, TCP/IP, and JavaScript/AJAX for iPhone chat Integrating WebSockets into a Cocoa application Hello all, our team is embarking on creating a bespoke iPhone chat app and deliberating the use of WebSocket ...

Obtaining a timestamp from a date string with a specific timezone/locale is simple and

I need to extract timestamps from JSON items with a date field formatted like this: 'Wed, 14 May 2014 20:19:00 BST' Is there a way to retrieve the timestamp from this specific string format? Attempting to create a Date object doesn't seem ...

Refresh Form Following Submission

When using a react form that triggers a graphql mutation upon button click, the text entered in the form fields remains even after the mutation has been executed. This necessitates manual deletion of text for subsequent mutations to be run. Is there a way ...