Discover the property associated with a specific value within a JavaScript array

My data is organized in the following structure:

var states = {
  'alabama': { abbv:'AL', ec: 9, winner: 0},
  'alaska': { abbv:'AK', ec: 3, winner: 0},
  'arizona': { abbv:'AZ', ec: 11, winner: 0}
}

If I wanted to locate "Alaska" by searching for "AK", how could I accomplish that?

Answer №1

Loop through the state names (keys) and utilize the find function to find the correct state.

var states = {
  'alabama': { abbv:'AL', ec: 9, winner: 0},
  'alaska': { abbv:'AK', ec: 3, winner: 0},
  'arizona': { abbv:'AZ', ec: 11, winner: 0}
}
const searchFor = "AK"
const foundState = Object.keys(states).find(stateName => {
  return states[stateName].abbv === searchFor
})

console.log(foundState)
// => "alaska"

console.log(states[foundState])
// => { abbv:'AK', ec: 3, winner: 0}

Answer №2

There are numerous ways to implement this functionality. Below is an example of a dynamic approach that takes a source, 'prop' (property), and a value as parameters:

function findObjectByProperty(source, prop, value) {
  let item = Object.keys(source).filter(key => source[key][prop] === value);
  if (item){
    return source[item[0]];
  }

  return null;
}

let alaska = findObjectByProperty(states, 'abbv', 'AK'); // -> retrieve the object for Alaska from the states object!

Simply provide the arguments 'states', 'abbv', and 'AK' when calling the function.

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

Tips for using parsley on a dynamically loaded webpage

I'm encountering an issue with applying validation for a datepicker in AJAX loaded content. The validation doesn't seem to work for the loaded content. Can someone please assist me with this? /Script/ function applyValidationForDatepicker(feest ...

What is the best method for toggling between three different elements in an array?

I have been working on a language switcher feature in my Next.js project. The idea is to have three languages available, with the ability for the user to click on a language and have it become the active one, while moving the previously active language t ...

React Hamburger Menu not working as intended

I am facing an issue with my responsive hamburger menu. It is not functioning correctly when clicked on. The menu should display the navigation links and switch icons upon clicking, but it does neither. When I remove the line "{open && NavLink ...

The preselected value in an AngularJS select box is set to static HTML by

In my HTML, I have a select tag that I am populating using ng-repeat. <td> <select ng-model="item.data.region" style="margin-bottom: 2px;"> <option ng-repeat="region in vm.regions track by $index" value="{{region}}">{{region} ...

Scope-specific dynamic variable name

When attempting to create a dynamic variable name within an AngularJS foreach loop, I encountered the following issue: angular.forEach($scope.posts, function (item) { // counter increment counter++; var idPage = 'feed' + counter; ...

Using the "bind()" method within a routed component

Here is a simplified Angular 1.5.x component example that I've set up in a jsfiddle: appModule.component('mainComponent', { controller: function() { var x = 0; this.broadcast = function() { this.onUpdate({ count: x++ ...

Creating a seamless integration of elements from two Vue.js components

As I work on developing the checkout page for an e-commerce app, I encounter the need to display a list of OrderItems from the database, each with its price and quantity. These items can be selected and grouped together. Additionally, I must also include a ...

How to Retrieve Multiple Data by Utilizing Json with the Help of jQuery and Ajax

I am facing a challenge in using two Linq-to-SQL statements to retrieve data from a database and populate an array for use in a jQuery call. While I have been successful in returning one array as Json, I'm unable to fetch the second array, which holds ...

"Have you ever wondered how the router object in express.js is seamlessly integrated with app.use(), considering that it only accepts

I am curious about the process of how the router object in express.js is passed to app.use(), which typically only accepts callbacks. Since router is an object of express, I am trying to understand why app.use() does not throw an error even though it req ...

Is it possible to sort an array by both date and time simultaneously?

As I work on developing a schedule app, it is necessary to sort items by both date and time simultaneously. In the current setup, the filtering only considers hours and minutes which is functional, but there is a need to also include dates in the sorting p ...

Leveraging Multiple Angular.js Controllers within a Shared DOM

As someone who is fairly new to Angular.js, I am currently working on integrating it into my Node.js application. While I have successfully created a RESTful API using Angular for a single controller, I am now looking to utilize two or more controllers wi ...

CSS2DRenderer Reset Feature

My scene, camera, renderer, and CSS2DRenderer are created using this class. I am looking for a way to reset (delete and add again) my CSS2DRenderer in order to remove any previously rendered CSS2DObject. Can you guide me on how to achieve this properly? T ...

Steps to generate a new page when submitting a form:

When a form is submitted, I am aiming to generate a fresh page each time. This new page will serve as an order status tracker that will be updated regularly. Essentially, my goal is for users to see a confirmation page for the form submission and have acce ...

What could be causing this React/Javascript object to be undefined?

I've been attempting to convert this JSON into JavaScript objects, but all my efforts have resulted in undefined values. The objects simply won't work as intended. Here is the code I'm using with the getStaticProps method to extract objects ...

Transforming a string into an array containing objects

Can you help me understand how to transform a string into an array of objects? let str = `<%-found%>`; let result = []; JSON.parse(`["${str}"]`.replace(/},{/g, `}","{`)).forEach((e) => ...

Enhancing ASP.NET MVC 5 Application with jQuery Validate: Implementing Submit Button Click Events

In the process of developing an ASP.NET MVC 5 application, I find myself faced with a dilemma. The current setup involves using the jQuery Validate plug-in that comes packaged with MVC applications. Upon clicking the "submit" button, jQuery Validate kicks ...

JavaScript's counter variable can become confusing when used in an if statement

Struggling as a beginner in javascript, I find myself stuck on writing an If statement that triggers after the fourth turn. My goal is to have an alert pop up once the user has clicked on four options. The counter variable "turns" was added to track prog ...

Swapping a Cube Mesh for a Car Mesh in ThreeJS

After developing a 3D cube that moves on one axis simulating the accelerometer sensor, I encountered errors when attempting to replace it with a car mesh. The errors are persistent and related to object definitions: https://i.sstatic.net/iTbGI.png Even t ...

Issues with the functionality of the login page's HTML and JavaScript

Recently, I attempted to create a login page with the following code: const loginForm = document.getElementById("login-form"); const loginButton = document.getElementById("login-form-submit"); const loginErrorMsg = document.getElementById("login-error-m ...

Transform the Hue or Color of a PNG using ASP.Net, VB.Net, and jQuery

I am currently developing a web page that can combine multiple PNG images into one flat image for users to download. I am looking to incorporate a feature that allows for hue or color adjustments, similar to the color balance functionality in Photoshop. ...