Retrieve records using any field in Javascript

Looking to work with an array of JavaScript objects, each containing three fields:

var people = [
  {first: "john", middle: "james", last: "doe"},
  {first: "jane", middle: "kate", last: "smith"},
  ...
  {first: "kathy", middle: "rose", last: "green"},
];

The goal is to query this array based on any field and receive the matching object as output. For example, being able to execute people.getByMiddle("kate") and retrieve

{first: "jane", middle: "kate", last: "smith"}

Wondering if there's a data structure that simplifies associating these elements or if it's better to create individual functions for each field to iterate over the data and search for matches. The primary concern is avoiding dependency on array ordering.

Answer №1

To streamline your code, consider implementing a helper function:

/**
 * Look for a specific object within an array and return the first match.
 * @param {array} grouping - an array of objects.
 * @param {string} identifier 
 * @param {string} criteria
 * @returns {object|undefined} - the first matching object.
 */
function locateElement(grouping, identifier, criteria) {
   return grouping.filter(function(item) {
      return item[identifier] === criteria;
   })[0]; // extract the initial match
};

var individual = findWhere(peopleArray, 'middleName', 'Jane');

Answer №2

function findObjectByProperty(arr, property, value) {
    arr.forEach(function(item) {
        if (item[property] === value) {
            return item;
        }
    });
}

To utilize this function:

var result = findObjectByProperty(users, 'lastName', 'Smith');

Answer №3

Consider this potential resolution:

function locateIndividuals(dataArray, propertyKey, query) {
  return dataArray.filter(function(individual){
    return query.test(individual[propertyKey]);
  })
}

See it in action: http://example.com/jsbin123

Answer №4

Here is a solution that comes to mind:

let members = [
  {first: "Alex", middle: "Lee", last: "Johnson"},
  {first: "Emily", middle: "Grace", last: "Smith"},
  {first: "Michael", middle: "David", last: "Jones"},
];


members.getByMiddleName = function(name){ 
   let result = [];
   for(let i in this){
      let person = this[i];
      if(person.middle == name)
         result.push(person);
   }
   return result;
};

members.getByMiddleName("Grace");

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

Using handleSubmit as an asynchronous function triggers an error because createUser is not a defined function in this context

I've been working on implementing user Authentication, login, and signup features. Everything was going smoothly until I encountered an issue while trying to sign up - it kept saying that createUser is not a function. SignUp Component code snippet wit ...

Tips for generating documentation using markdown within the docs directory on GitHub with the help of JavaScript

After browsing through numerous documentation websites, I have noticed that many of them share the same layout and features. This has led me to question whether there is a common library used by all these documentation sites. How do they achieve this unif ...

Is it time to switch up your header text?

I'm currently facing an issue with the following code: HTML: <button id='ro' class='ro'></button> <button id='eng' class='eng'></button> JAVASCRIPT: $('#ro').click ...

What is the best approach to integrating an idle timeout feature with identityserver4 and aspnet identity for a secure implementation?

Currently, I am developing a login site using IdentityServer4 (server UI) with .NET Identity in .NET Core 2.2 Razor Pages. I have implemented a javascript modal alert that notifies users of an impending idle timeout and redirects them to the logout screen ...

defiant underscore refusing to function

I'm currently working on a text editor, but I'm facing an issue with the remove underline functionality that doesn't seem to be working as expected. For reference, you can check out a working code example here: jsfiddle Below is the part of ...

My JavaScript if-else statement isn't functioning properly

I'm facing an issue with my if statement not functioning correctly when trying to validate non-numeric inputs for the weight variable upon submission. What could be causing this problem? submitBtn.onclick = function(){ var name = document.get ...

Click a button to adjust the height of an element

My webpage features a dashboard with tabs on the left and corresponding content on the right. To ensure proper alignment, I have utilized Bootstrap to create two columns - one for the tabs and one for the content. However, I am facing an issue where the bo ...

Retrieving, storing, and implementing the classes of child elements directly from an array using jQuery

With the help of jQuery, you can retrieve child elements of the #parent element that have the class .west. In this case, we are not interested in fetching the content of these child elements but instead their class names. For example: <div id="parent" ...

What sets Vue.js apart, class and staticClass - is there a distinction?

Can someone explain the distinction between class and staticClass in Vue.js render functions? While using Template Compilation, I noticed that the output varies based on what is provided to the HTML class attribute. For instance, when passing a single str ...

Is there a way to make elasticX() and elasticY() only affect the upper bound in dc.js?

One question I have regarding my bubbleChart in dc.js is related to the x-axis. I want the count on the x-axis to always start at 0, but have an upper bound that adjusts based on the range I am looking at. Currently, when I use .elasticX(true), both the up ...

I am attempting to save the input value to an array in local storage using VUEX. However, my current method is not producing the desired results

I am facing an issue where I am trying to push an input value and store it in an array in the local storage using VUEX. I have created an array in the state for this purpose. Initially, I push the value and then I stringify it to set the value to the sto ...

Get a new perspective from a different page's refresh

I have a unique situation where I am working on a project that involves two separate pages, each displayed on different computers. What I hope to achieve is that when I click a button on the first page, it triggers a refresh of the second page. Is there a ...

Prevent dropdown from closing when clicking inside components [react-bootstrap]

I am searching for a solution to hide a drop-down bot by clicking on elements inside it. I am exploring different methods using JQuery. Is it possible to achieve this using JavaScript in combination with react-bootstrap? My current approach involves calli ...

Having trouble turning octet-stream response data into a downloadable Zip file

I've been attempting to download a Zip file that contains JSON files through an AJAX GET request. Here is the format of the response headers: Connection: keep-alive content-disposition: attachment;filename=exportedFiles_ 1.6.0_20200731160652.zip Cont ...

I am interested in implementing a logout feature using a button in PHP

<?php session_start(); ?> <form> <input type="button" id="logout" value="logout" name="logout"> </form> After initializing the session during login, I am seeking to terminate it using a button rather than via <a href="">l ...

Retrieve the values of all child attributes in the XML file

This is a sample XML structure: <child_2 entity_id="2" value="Root" parent_id="1"> <child_4 entity_id="4" value="Activities" parent_id="2"> <child_10066 entity_id="10066" value="Physical1" parent_id="4"> <child ...

Using Promise.map inside another Promise.map

Attempting to return a JSON object via Bluebird's Promise.mapSeries/Promise.map nested within another Promise.mapSeries/Promise.map is proving difficult. Below is the code snippet for the function: function getMovieDetails(link){ return new Promise(f ...

How can jQuery dynamically append query strings to script loads?

After adding the following JavaScript to my page: $("#divExample").append("<script type='text\/javascript' src='\/scripts\/test_code.js'><\/script>"); A request is being made to: http://.../scripts/tes ...

PHP list() function issue: "Offset not defined"

In my current project, I am receiving unexpected errors from a system in the form of a string containing error type, message, and details. An example of this format is: Error Type - Database Error Message - Error Executing Database Query. ...

Angular.js filter issue: "Error: textProvider is not recognized provider"

I implemented a custom filter for my AngularJS project that is similar to the one in this fiddle http://jsfiddle.net/tUyyx/. myapp.filter('truncate',function(text,length){ var end = "..." text = text.replace(/\w\S*/g, function( ...