Tips for locating a key within an object that houses a specific value in its array

In my Coffeescript code, I have created the following Javascript object:

urlSets =
  a: [
    'url-a.com'
    'url-b.com'
    'url-c.com'
    ]
  b: [
    'url-d.com'
    'url-e.com' 
    'url-f.com'
    ]
  c: [
    'url-g.com'
  ]

If I have the value "url-a.com", how can I determine the key</cde> in <code>urlSets that contains this URL?

I am currently using the underscore.js library, and I thought about using _.findKey along with _.contains. My attempt looks like this:

_.findKey urlSets, (key) ->
  return _.contains(key, "url-a.com")

However, this approach is not working as expected and results in a

TypeError: undefined is not a function
.

Answer №1

Personally, I prefer not relying on any external libraries when it comes to looping through data, especially with the convenience of CoffeeScript's loops.

foundKey = null

for key, urls of urlSets
  if 'url-a.com' in urls
    foundKey = key

console.log foundKey #=> a

This code snippet utilizes a for key, value of object loop to easily iterate through the urlSets object and then performs an if item in array check which CoffeeScript compiles into an indexOf call.

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

Adjust the size of the text within the div element as needed

Here is my code on jsFiddle where I am dynamically changing the text font to fit in the div. Everything is working perfectly fine. Currently, the text is within a span element, but I would like to remove the span and have the same functionality. However, w ...

What causes the parent element's click event to trigger on its own when a child textbox is clicked or focused in Safari?

Describing my HTML setup [Checkbox] [Text] [Input element (Display if check-box is marked)] <span class='spGrpContainer'> <label id='stepGH_Group1' class='lblStep GHSteps lblGroupheader' stepid='1' st ...

Is there a way to modify Style Properties in JavaScript by targeting elements with a specific class name using document.getElementsByClassName("Class_Name")?

I am seeking a solution to change the background color of multiple div boxes with the class name "flex-items" using JavaScript. Below is my current code: function changeColor(){ document.getElementsByClassName("flex-items").style.backgroundColor = "bl ...

Preserving Scroll Location Through Back Button Usage and Ajax Manipulation of the Document Object Model

Currently, I am incorporating a feature where results are loaded in using ajax with an infinite scroll. However, there is an issue when a user clicks on an item in the list and navigates away from the page - upon returning by clicking the back button, they ...

Leverage the power of the YouTube API to determine if a video is able to be embedded

As I delve into the YouTube Data API v3 to determine if a particular video is embeddable, I have come across the status.embeddable property that seems crucial. By making a request like this: https://www.googleapis.com/youtube/v3/videos?id=63flkf3S1bE& ...

Differentiating Between Observables and Callbacks

Although I have experience in Javascript, my knowledge of Angular 2 and Observables is limited. While researching Observables, I noticed similarities to callbacks but couldn't find any direct comparisons between the two. Google provided insights into ...

I need help figuring out how to set the country code as uneditable and also display a placeholder in react-phone-input-2 with React

How can I display the placeholder after the country code without allowing it to be edited? Currently, it's not showing up in my React functional components. Here is the code snippet: <PhoneInput className="inputTextDirLeft" ...

Can you provide guidance on implementing StyledComponents within the app folder of Next.js version 13?

Quoting information from the Next.js documentation: Attention: CSS-in-JS libraries that rely on runtime JavaScript are currently not compatible with Server Components. The following libraries are supported in Client Components within the app directory: s ...

Retrieve the image by its unique identifier while viewing a preview of the image before it is uploaded

Below is the script I am using to preview an image before it is uploaded. The HTML structure looks like this: <div> <img id="image" src="#"> </div> <input type="file" accept="image/gif, image/jpeg, image/png" onchange="readURL(th ...

Step-by-step guide on dynamically adding "Input Tags" to the DOM at runtime using Selenium's JavascriptExecutor

In order to dynamically add the following element to the DOM during run time, I need assistance... <input type="text" name="imagesToAdd" value="3566"> My initial attempt was to use Selenium JavascriptExecutor for this task. However, I encounter ...

javascript + react - managing state with a combination of different variable types

In my React application, I have this piece of code where the variable items is expected to be an array based on the interface. However, in the initial state, it is set as null because I need it to be initialized that way. I could have used ?Array in the i ...

The Next.js dynamic route in production is displaying a 403 error instead of the expected 404. What might be causing this issue?

Whenever I attempt to access https://site.con/categories/, I am greeted with a 403 Forbidden error. However, if I visit https://site.con/categories/sport, everything works perfectly fine, and all other routes function properly. What could potentially be ca ...

Updating the Background Color of a Selected Checkbox in HTML

I have a straightforward question that I've been struggling to find a simple answer for. Can anyone help me with this? Here's the checkbox code I'm working with: <input type="checkbox"> All I want to do is change the backgr ...

Enhancing parent component props in React-router-dom: A guide to updating them

Here is the structure of my App component: const App = (props) => ( <BrowserRouter> <PageTheme {...some props I'd like to change on route change}> <Switch> <Route exact path="/example"> <E ...

Can Flask convert a JSON Array object into a Python string?

When I receive a JSON-encoded parameter in my Flask server via an HTTP POST from the client application, the JSON object structure seems to be causing some confusion. In this example, I have included only the first 2 entries of the JSON object for simplic ...

React - Utilizing Secondary Prop Value in Material UI Node Components

I've been working on streamlining my code and am wondering about the best way to pass an additional value using props while fetching data from the backend. I'm utilizing material UI's Autocomplete with the PERN stack. Everything is functioni ...

Node.js JSON parser encountering an unexpected undefined error

Whenever I attempt to JSON.parse the string, an error occurs and I receive this message: undefined:1 {"device":"FaclonTest","data":[{"tag":"LATITUDE","value":1903.5091},{"tag":"LONGITUDE","value":07251.0348}]} I'm unsure of where the mistake is. Can ...

Adjust the text size of a label in material-ui

Hey everyone, I'm struggling with something here. I need to adjust the font size of the label that goes along with my textfield. So far, I've only been able to change the font size of the input itself and not the label. Here's the code for ...

React: When mapping an array of state objects, not all states are displayed

I'm encountering an odd problem while using React. I'm currently developing a budget tracking app that includes a total budget, a form to add new expenses, and displaying those expenses with their costs below. The cost of the new expense will als ...

Adding a Timepicker to a Datepicker on a jsp webpage with javascript

I am working on a JSP page that includes a date picker. I want to enhance this datepicker by adding a start time and end time within the calendar itself. How can I achieve this? Additionally, I need to implement validation ensuring that the start time is a ...