0

If I have something like this:

var cars = [
{car:"01", color:"red", date: Date("Sep 23, 2013 12:00:00")},
{car:"02", color:"blue", date: Date("Sep 24, 2013 12:00:00")},
{car:"03", color:"green", date: Date("Sep 25, 2013 12:00:00")},
{car:"04", color:"yellow", date: Date("Sep 26, 2013 12:00:00")},
{car:"05", color:"purple", date: Date("Sep 27, 2013 12:00:00")}];

and I want to: 1) select an item car:"03" for example, how do I do this? I thought of doing something like this, just for testing, but this didn't work out:

$(cars).each(function(i,el) {
    console.log($(this).car);
});

and 2) is this valid to compare this kind of Date in the array to real current Date? for example:

var currentDate = new Date();
if ( currentDate < Date ) { ...

Thanks!

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
memime
  • 5
  • 1
  • I wouldn't use car:01 or car:02 and so on. There is already key on every object in your array, so you can access car: 03 by just getting cars[2] (because keys start with 0 not 1) – Imphusius Jan 02 '17 at 16:55
  • Thanks. Following your logic, tried to do `console.log($(this).car[i]);` but this didn't work out too... I'm using "01", "02", "03" etc not as an index, but as a car number. it may be 10th in the array, but "33" as a number next to it – memime Jan 02 '17 at 16:58

1 Answers1

0

You want to look for the property car on each object and compare it's value to the value you are searching for

Also use $.each() to iterate arrays or objects instead of $.fn.each() which is really intended for use with element selectors

$.each(cars, function(i, el) {
    if(el.car === '03'){
        console.log(el);
    }        
});

There are other native array methods you can use like Array.prototype.find() but i stayed with $.each to maintain consistency with question code

As for the date comparison ...yes you can directly compare date objects using < or >

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Thank you very much, Charlietfl! Could you please tell me how may I take the value of the "car"? For example if I don't know the value, I won't be able to compare it, so I would need to check it and get it somehow. – memime Jan 02 '17 at 17:08
  • Take it from where though? – charlietfl Jan 02 '17 at 17:09
  • From the array of "cars". For example, if for some reason I don't know exactly what is the "car" number, or "color"... how could I get this? – memime Jan 02 '17 at 17:16
  • well you need to know one property value (or be able to get it from some sort of event) in order to get another. – charlietfl Jan 02 '17 at 17:18
  • Ok Charlietfl, thanks – memime Jan 02 '17 at 18:03