[英]Filter an array of objects within an object
我有以下內容;
var room = function(){
this.entities = new Array();
}
var myRoom = new room();
我也有很多這樣的實體。
var entity = function(){
this.title = "A pillow";
this.noun = "pillow";
}
我可以將許多實體推入myRoom.entities數組。
現在,我想檢查一個房間是否包含基於其名詞的特定實體。
我已經嘗試過這樣的事情;
var objPillow = myRoom.filter(function (object) { return object.entities.noun == "pillow" });
但這是行不通的。
JavaScript filter
是一個數組方法(請參閱文檔 )。 您應該改為在對象的entities
屬性上調用它:
var objPillow = myRoom.entities.filter(function (entity) {
return entity.noun == "pillow"
});
基於您的短語“現在,我想檢查一個房間是否包含基於其名詞的特定實體 ”,因此您不需要該實體本身,而只需檢查其存在:
function check(noun){
return myRoom.entities.some(function(a){ return a.noun === noun; })
}
var sample = new Entity();
sample.noun = "Test";
sample.title = "Anything";
myRoom.entities.push(sample);
check("Test"); //>>true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.