0

I have a list of objects, in each object I have a date and time.

onClick of a td element (its a calendar) I check the time on the calendar, then check if it matches any times in my list of objects.

onSelect: function(date) {
    for (var i = 0; i < dateArray.length; i++) {
        for (var prop in dateArray) {
            if (date === dateArray[prop].date) {
                console.log(dateArray[prop].time);
            }
        }
    }
}

So I loop through my array, which is an array of objects. To be able to get anything out I need to do a for in loop, and in there I do a condional statement to say if the dates match. The console.log out the corect time.

However, the time gets console logged out 10 times since it's in a loop. But the only way I could get inside my object array was to loop through them.

How should I actually be doing this.


EDIT

dateArray structure: list of objects like [ object, object, object, object ] and once I loop through them, within each object it looks like :

Object {title: "The Title", date: "01/01/2017", time: "07:30pm", available: true,}
5
  • use indexOf function in javascript. If value is there it will return index or it will return -1. Commented Jun 22, 2016 at 6:42
  • does for (var prop in dateArray) actually give you an index number to use in dateArray[prop]? shouldn't you be using i? Commented Jun 22, 2016 at 6:47
  • @Coderchu I don't know if I should be looping twice. Date is coming from jQuery Date picker. It's basically a list of all the dates in the current month. Commented Jun 22, 2016 at 6:48
  • You should show us the structure of the dateArray Commented Jun 22, 2016 at 6:49
  • 1
    @FrancescoD'Alesio Sorry! Just updated it now with the sturcutre of dateArray Commented Jun 22, 2016 at 6:51

1 Answer 1

2

I think you are simply looping twice.

Given it is an array, you should loop it using for, like this

onSelect: function(date) {
    for (var i = 0; i < dateArray.length; i++) {
        if (date === dateArray[i].date) {
            console.log(dateArray[i].time);
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Dude that was it! I should of been using i instead of doing another for...in loop. Sorry, amateur hour over here :) thanks man!

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.