私はオブジェクトの配列を持っています。各オブジェクトには、available
と呼ばれるブール値のプロパティと、任意の数の他のプロパティがあります。私はavailable
プロパティが存在することを知っていますが、他のプロパティは何か分かりません。例えば:valueのペアと一致し、利用可能なこれらのオブジェクトを返します。Javascript:特定のプロパティと値を持つ配列内のすべてのオブジェクトを見つける
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},
]
私は、任意の属性を取ることができます機能isAvailable()
を必要としています。例えば、私は100
の色で利用可能なオブジェクトのために要求された場合、それが唯一の第一および第三のオブジェクトからなる配列を返すことになる。
>> isAvailable({color:100})
Array [ {color:100, size:12, available:true}, {color:100, size:18, available:true} ]
しかし、私は100
の色とAとのオブジェクトのためにそれを依頼された場合長さが86
、またはちょうどサイズが13
の場合、空の配列が返されます。
>> isAvailable({color:100, length:86}) // there are no objects with both of these properties
Array [ ]
>> isAvailable({size:13}) // there is a matching object, but it is not available
Array [ ]
私は機能していますが、それほど美しくはありません。 JavaScriptについての経験はあまりありませんが、これについてもっと良い方法があるかどうかはわかりません。
function isAvailable(options) {
var availableObjects = [];
// get the number of objects
var numObjects = myObjects.length;
// get the number of options that were given
var numOptions = Object.keys(options).length;
// loop through each object
for (var i = 0; i < numObjects; i++) {
var thisObject = myObjects[i];
// default the matching to false
var match = false;
// loop through each option and check if the current object has the option and, if so, if the values are the same.
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;
}
誰でもこれに関するフィードバックを提供できますか?ありがとうございました。
'.filter'をチェックアウト - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter – Adam
は、アンダースコアのように聞こえます'.find()'メソッド – dandavis