0

How can i get the second values (dates) in a javascript array?

I am new to this and i can't get it to work.

{"0":"11-28-2012","4":"11-29-2012","10":"12-03-2012"} 

Thanks!

intelis
  • 7,829
  • 14
  • 58
  • 102
  • You should be able to do this by simply doing `json_object[1]`. – Jeremy Dec 04 '12 at 02:15
  • See this question: [loop-through-javascript-object](http://stackoverflow.com/questions/684672/loop-through-javascript-object) – DanneManne Dec 04 '12 at 02:18
  • What do you mean by "second dates"? The object you have does have no ordered values, and no key "1". – Bergi Dec 04 '12 at 02:21

3 Answers3

1

A very simple loop is below. You should check that the object hasOwnProperty which is important for more complicated objects.

If your object is called obj:

obj = {"0":"11-28-2012","4":"11-29-2012","10":"12-03-2012"}; 
for (var i in obj) {
    console.log(obj[i]);
}

Or without the loop:

obj = {"0":"11-28-2012","4":"11-29-2012","10":"12-03-2012"};
console.log(obj[0]); // displays "11-28-2012"  
timc
  • 2,124
  • 15
  • 13
  • 1
    You should not name the object "`arr`", as it is no array. – Bergi Dec 04 '12 at 02:20
  • You are completely correct, I have updated the answer. Thanks. – timc Dec 04 '12 at 02:21
  • Hi, thanks for your answers, but i cant get it to work. I have a PHP that does json_encode on array, and then when i console.log() the returned array via ajax i get that object returned, but i cant loop through it..http://jsfiddle.net/qL6dk/ – intelis Dec 04 '12 at 02:25
  • Unfortunately I can't get your fiddle to work for me. What happens when you try to loop through it? – timc Dec 04 '12 at 02:34
  • it looks like its returning parts of string..it does not recognize it as object.. – intelis Dec 04 '12 at 02:43
  • i got it to work..for (i in ret) { console.log(ret[i].attributes.datum); } – intelis Dec 04 '12 at 02:48
  • Nice one, there must be more to the object than specified. – timc Dec 04 '12 at 02:55
0

In javascript, the order of keys is nondeterministic. if you really want, you can use underscore values function

_.values(obj)[1]
Ping Yin
  • 31
  • 2
0

Not really sure want do you want. But if you want to get date in month-date-year use split().

var jsonDate = {"0":"11-28-2012","4":"11-29-2012","10":"12-03-2012"};

console.log(jsonDate["0"].split('-')[1]); //28
console.log(jsonDate["4"].split('-')[1]); //29
console.log(jsonDate["10"].split('-')[1]); //03
OammieR
  • 2,800
  • 5
  • 30
  • 51