Determine the existence of a specific array key in JavaScript by utilizing regular expressions

I'm trying to search through an associative array to find a key that ends with the letter "r". When I use the "in" javascript keyword with a static string, it works fine but not when using regex dynamically.

Answer №1

Object.keys(obj) retrieves the keys from the object and returns them as an array. This array can then be filtered using Array.prototype.filter to extract specific keys:

filteredKeys =
  Object
    .keys(obj)
    .filter(function (key) {
      return /pattern/.test(key);
    });

Answer №2

Loop through the object's properties and check if they match a specified expression. If there is a match, return the name of the property.

function findMatchingProperty(expression, obj)
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            if (expression.test(prop)) {
                return prop;
            }
        }
    }
    return null;
}

If you need to get all matching property names:

function findAllMatchingProperties(expression, obj)
    var matches = [];
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            if (expression.test(prop)) {
                matches.push(prop);
            }
        }
    }
    return matches;
}

Answer №3

If you need a quick and dirty test, you can use this approach:

/r":/.test(JSON.stringify(data));

Additionally, zzzzBov's functional solution leveraging Array.prototype.some() can also be implemented like this:

Object.keys(data).some(function (prop) {
  return /r$/.test(prop);
});

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

Undefined variables are returned by declarations in a script setup after an asynchronous call with top-level await

Here is the structure of my Nuxt 3 / Vue 3 component using script setup: <script setup> const content = await useFetch('/api/items/published').then((res) => res.data) const items = await content.data.items const issues = awai ...

In dire need of assistance with dividing an array into a menu using JavaScript before my brain implodes

With the usage of Javascript, I am dealing with an array structured as follows: [{"id":171, "children": [{"id":172}, {"id":170}, {"id":173}]}, {"id":174}, {"id":175}] This array is created from a nestable jQuery list. Now, I have the require ...

Efficient way to trim array elements value in PHP without using a foreach loop

I have a PHP code snippet that I am currently using: Code: $input = array(" text1","text2 "," text3 "," text4"); $output = array_map('trim', $input); var_dump($output); Can the values of array elements be trimmed without usin ...

JavaScript - What is the best way to add the same object value into an array?

After spending a few hours trying to figure out how to manage JSON data structured like this: [ { "value": "Osteonecrosis", "Diagnosis_Code": "DIAG002", "NamaCategory": "Primary Category", "FK_Diagnosis_Content_ID": 2 }, { "value ...

How to extract JSON array from JSON object in Swift 3

I'm experiencing difficulties with parsing a JSON array within JSON data because the JSON array I receive isn't always an array. The key of the array is Body based on another parameter called infoType. The value of Body can be either an array or ...

What is the best way to populate a select input field with options using JavaScript?

When I am loading an HTML table, there is a select input field that needs to display some options. Immediately after constructing the HTML table row, I invoke a function to populate this input field using its class. Below is the relevant HTML snippet and ...

Display loading screen during the setup of the main page

Is there a way to display a preload image while the main page is being prepared and loaded, without using Ajax? I need to reload the entire main page, so I'm considering the following approach: First, request the preload page from the server. Second, ...

The module.run function in Angular is invoked with each individual unit test

Hey there I am currently working on setting up jasmine-karma unit tests for my angular app. The problem arises in my app.js file where the module.run method is calling a custom service (LoginService) that then makes a call to the $http service. The issue ...

What is the best way to retrieve data attributes from multiple div elements that share the same class name?

I have multiple div elements with the same class name. I want to extract the data attribute from these div's. I have tried some code and managed to get the result. However, I am unsure if this is the best approach for retrieving data("cartid"). Any as ...

Guide to creating "bidirectional data binding" in Vue

I have a child component that is responsible for uploading a photo. The uploaded photo is assigned to the child component's data called "photo". I need to connect the parent data called "file" with the child data called "photo". And whenever "photo" i ...

I can't understand why this question continues to linger, I just want to remove it

Is there a valid reason for this question to persist? I'm considering removing it. ...

Organizing items by a string attribute in TypeScript

My data consists of an array of objects with a structure similar to this: export class AccountInfo { accountUid: string; userType: string; firstName: string; middleName: string; lastName: string; } NOTE: I opted not to use an enum for userType ...

Sending a parameter from MVC 3 to JavaScript

Is there a way for me to successfully send the parameter counter to my BindUnbind() function? <div id="adver-list"> @{ var counter = 1; foreach (var adver in (IEnumerable<string>)ViewBag.AdverImages) { ...

Unable to load physi.js and ammo.js due to a loading error

I'm currently working on a project involving physijs, but I keep encountering a specific error in Mozilla Firefox console: NetworkError: Failed to load worker script at "js/libs/ammo.js" https://i.sstatic.net/C41T8.png I've been trying to tro ...

Tips for extracting data from a <li> tag and storing it in a jQuery array

I'm struggling to extract the text from a list and store it in an array. However, instead of getting the content itself, I end up with a list of numbers. Does anyone have any suggestions on how I can successfully place the content in the array? var a ...

The functionality of the jQuery autocomplete textbox seems to be malfunctioning when used in conjunction with an update panel

Having trouble getting the result after unloading jQuery? How do you reload it when the update panel is updated? Any solutions to overcome the issues with jQuery and the update panel? <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.a ...

Issues with Jquery show and hide functionality within a list element

My menu items are displayed using show and hide functions, sliding up and down on hover. The issue I am facing is that when a list item expands, the overall background of the menu also expands. However, when it contracts, the background also contracts. If ...

retrieve trackpoint information using OpenLayers

When displaying a map with a GPX track using OpenLayers 5.3, I noticed that the trackpoints default to a MultiLineString geometry type. The example provided in the GPX-example actually has a larger file size because all of the <trkpt> tags are duplic ...

"Enhancing user experience with CSS hover effects on dynamically loaded content and mobile devices

I have developed a quiz with 2 answer options for each question. To prevent the questions from loading initially, visitors must click a start button, triggering the questions to load via Ajax. The issue I am facing is that when a question is answered, the ...

An anomaly where a mysterious symbol appears in front of every dollar sign in an HTML document

I have a code written in AngularJS to display the amount in dollars. However, there is an unwanted " Â " character appearing before every " $ " character in the HTML. I am looking for a way to remove this character. Your help is greatly appreciated. Thank ...