2

I have the following;

var room = function(){
    this.entities = new Array();
}
var myRoom = new room();

I also have a bunch of entites like this;

var entity = function(){
    this.title = "A pillow";
    this.noun = "pillow";
}

I can push many entities into the myRoom.entities array.

Now I want to check to see whether a room contains a particular entity based on its noun.

I've tried something like this;

var objPillow = myRoom.filter(function (object) { return object.entities.noun == "pillow" });

But it doesn't work.

3
  • How are you pushing entities into myRoom.entities? What does “doesn’t work” mean? Commented Nov 13, 2013 at 0:29
  • Why did you remove the second example of what you've tried from your question? Commented Nov 13, 2013 at 0:30
  • I removed it because it did work and I was alerting it out wrong. Commented Nov 13, 2013 at 0:35

2 Answers 2

3

Based on your phrase "Now I want to check to see whether a room contains a particular entity based on its noun.", so you don't need the entity itself, but to check for its existence:

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
Sign up to request clarification or add additional context in comments.

1 Comment

Actually that's fits better with my question but both you and @net.uk.sweet have helped solve the issue. and yeah, based on my phrasing this is more correct.
3

JavaScript filter is an array method (see documentation). You should call it on the entities property of your object instead:

var objPillow = myRoom.entities.filter(function (entity) { 
  return entity.noun == "pillow" 
});

3 Comments

Erm, yes. Missed that one. Thanks
Sorry but based on my phrasing of the question the other answer is more correct though i will also be using this answer. thanks again.
That's cool. I went straight to the code, Alcides read and understood the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.