Javascript code for identifying objects in an array with specific properties and values

I have a collection of objects. Each object contains a boolean property named available, along with various other properties. While I am aware that the available property is present, the rest of the properties are unknown. For example:

var myObjects = [
    {color:100, size:12, available:true},
    {color:100, size:13, available:false},
    {color:100, size:18, available:true},
    {color:110, size:12, available:true},
    {length:86, available:true},
]

I require a function called isAvailable() that can accept any attribute:value pairs and retrieve the objects that match the criteria and are available. For instance, if I request available objects with a color of 100, it should return an array containing only the first and third objects:

>> isAvailable({color:100})
Array [ {color:100, size:12, available:true}, {color:100, size:18, available:true} ]

If I ask for objects with a color of 100 and a length of 86, or objects with just a size of 13, the function should return an empty array.

>> isAvailable({color:100, length:86}) // no objects have both these properties
Array [ ]
>> isAvailable({size:13}) // there is a matching object, but not available
Array [ ]

Although I do have a functional solution, it lacks elegance. As I am relatively new to JavaScript, I wonder if there is a more efficient approach to solving this problem.

function isAvailable(options) {
    var availableObjects = [];
    var numObjects = myObjects.length;
    var numOptions = Object.keys(options).length;
    for (var i = 0; i < numObjects; i++) {
        var thisObject = myObjects[i];
        var match = false;
        for (var x = 0; x < numOptions; x++) {
            var thisOption = Object.keys(options)[x];
            if (thisObject.hasOwnProperty(thisOption) && thisObject[thisOption] == options[thisOption]) {
                match = true;
            } else {
                match = false;
                break;
            }
        }
        if (match == true && thisObject.available == true) {
            availableObjects.push(thisObject);
        }
    }
    return availableObjects;
}

Any suggestions or feedback on improving this code would be greatly appreciated. Thank you.

Answer №1

You can utilize the filter() and every() methods to achieve the desired outcome.

var myObjects = [
  {color:100, size:12, available:true},
  {color:100, size:13, available:false},
  {color:100, size:18, available:true},
  {color:110, size:12, available:true},
  {length:86, available:true},
]

function checkAvailability(obj) {
  var keys = Object.keys(obj);
  return myObjects.filter(function(item) {
    return keys.every(function(k) {
      return item.available && item.hasOwnProperty(k) && obj[k] === item[k]
    })
  })
}

console.log(checkAvailability({color:100}))
console.log(checkAvailability({color:100, length:86}))
console.log(checkAvailability({size:13}))

Answer №2

To filter arrays, you have the option to utilize the .filter() method. In cases where older browser compatibility is needed, using a library like Lodash can be helpful.

myObjects.filter(function(item) { return item["available"] === true && item["color"] === 100 })

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

What is the best way to use jQuery to update the color of an SVG shape?

Hello everyone! I'm excited to be a part of this community and looking forward to contributing in the future. But first, I could really use some assistance with what seems like a simple task! My focus has always been on web design, particularly HTML ...

Dealing with the issue of asynchronous operations in a controller using async/await function

Something strange is happening here, even though I'm using async await: const Employee = require('../models/employee'); const employeeCtrl = {}; employeeCtrl.getEmployees = async (req, res) => { const employees = await Employee.find( ...

Triggering a jQuery click event to showcase the hidden content

I am attempting to replicate the functionality seen on the website. The issue I am facing is related to the event_content class. I want to display only a limited amount of content initially, and then hide the excess content. Upon clicking the plus class, ...

What strategies can be utilized to manage a sizable data set?

I'm currently tasked with downloading a large dataset from my company's database and analyzing it in Excel. To streamline this process, I am looking to automate it using ExcelOnline. I found a helpful guide at this link provided by Microsoft Powe ...

Storing a variable in Vue on one page and accessing it on another page

Is there a way to transfer a value from config.js file to Geturl.vue? The content of the config.js file is as follows: var myUrl = "http://localhost:7070/#/"; The code snippet in my view file (Geturl.vue) is shown below: <div id="app>> <p ...

An unexpected page transition occurs when attempting to delete a link

I've successfully created an HTML table that dynamically adds rows and provides an option to delete the current row. Each row represents data retrieved from MongoDB, and upon clicking the delete button, I aim to delete the corresponding item from the ...

Setting default values for JSON objects by analyzing the data of other objects within the array

I've been grappling with this issue for about 6 days now, so please bear with me if my explanation is a bit convoluted. I'm using NVD3 to showcase graphs based on data retrieved from BigQuery. While the data and graph setup are correct, the probl ...

The basic node API request is not showing any information

There is a request in my server.js file var Post = require('./../models/post'); //GET ALL POSTS app.get('/api/posts', function (req, res) { Post.getPosts(function (err, posts) { if(err) { throw err; } ...

Getting around CloudFlare's 100-second time-out restriction

Seeking a solution to AJAX-enable my reports and circumvent the 100-second time-out constraint enforced by CloudFlare for requests passing through its platform. For more information, visit Is it possible to increase CloudFlare time-out? The implementatio ...

Extracting user login details from a Java script-based web browser for a RASA chatbot

Our website integrates a web bot using Javascript. When users log in, they can access the chatbot icon. Currently, the chatbot starts without collecting user data. However, having user data is important as we plan to trigger actions based on user ID. If ...

How do I retrieve the child elements of an array from a JSON response in ReactJS?

After receiving JSON data: componentDidMount() { const {axios} = this.props const {invoice} = this.state axios({ method: 'get', url: `/invoice`, }).then((re ...

Display or conceal a div based on the size of the screen using HTML and CSS

Hey there, I recently finished my first React Project and I’m wondering if there’s a way to hide the 'side-menu' section on mobile screens using CSS. Any suggestions? <div className='side-menu'> <SiderComponent /> < ...

Is there a way in AngularJS to set all radio buttons to false when one is chosen as true?

When I retrieve true/false string values from the database, I am unable to alter the data. The example I provided is simply a representation of the string values true or false that I receive from the database. My goal is to have a single radio button disp ...

Select three random items from a string array list along with their corresponding indexes using TypeScript in Angular

Consider this example: I am working with a string array const groceries = [ 'milk', 'coriander', 'cucumber', 'eggplant', 'carrot', 'brinjal', 'on ...

Scala's multidimensional array functionality can be further enhanced through the use of the

I am faced with a challenge involving two different arrays: val one = Array(1, 2, 3, 4) val two = Array(4, 5, 6, 7) var three = one zip two map{case(a, b) => a * b} While this solution works for the given arrays, my problem has evolved. Now, I have a m ...

Take out the bottom of the structure

Currently, I am utilizing ThreeJS to showcase a house model. My goal is to create a grassy area surrounding the house. However, I have encountered an issue where if the grass is simply a flat plane, it ends up appearing inside the house itself (as seen in ...

Step-by-step process for recursively reversing an array

Could someone provide a detailed explanation of how this recursive method reverses an array step by step? # Python program that recursively reverses an array # Function to reverse A[] from start to end def reverseList(A, start, end): if start >= ...

Guide on shifting an element into a different one with the help of jQuery

I'm attempting to relocate an element within another in order to enable a css :hover effect. <ul> <li id="menu-item"> //move into here </li> </ul> <div class="tomove">...</div> 'tomove' is set to dis ...

Building an Angular module that allows for customizable properties: A step-by-step guide

I am in the process of developing an AngularJS module that will simplify interactions with my product's REST API. Since my product is installed on-premise, each user will need to provide their own URL to access the API. Therefore, it is essential that ...

Parsing HTML to access inner content

Currently, I have integrated an onClick event to an anchor tag. When the user interacts with it, my objective is to retrieve the inner HTML without relying on the id attribute. Below is the code snippet that illustrates my approach. Any assistance in acc ...