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.