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!

3
  • You should be able to do this by simply doing json_object[1]. Commented Dec 4, 2012 at 2:15
  • See this question: loop-through-javascript-object Commented Dec 4, 2012 at 2:18
  • What do you mean by "second dates"? The object you have does have no ordered values, and no key "1". Commented Dec 4, 2012 at 2:21

3 Answers 3

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

7 Comments

You should not name the object "arr", as it is no array.
You are completely correct, I have updated the answer. Thanks.
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..jsfiddle.net/qL6dk
Unfortunately I can't get your fiddle to work for me. What happens when you try to loop through it?
it looks like its returning parts of string..it does not recognize it as object..
|
0

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

_.values(obj)[1]

Comments

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

Comments

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.