0

So, I have an array that contains X objects, all named by dates and containing useless data beyond their name. I want to store these dates in an array for later use and objects are, apparently, not found in an array by array[i], so how do I iterate through the array and just save the names to a string in another array?

Edit: Ok this question was due to a major brainfart... The obvious answer would be

    var dP = $('#calendar').GetDate();
    var dPTmp = [];
    var i = 0;
    for (var id in dP) {
        dPTmp[i] = dP[id].toString();
        i++;
    }
    console.log(dPTmp);
Mantar
  • 2,490
  • 5
  • 21
  • 30
  • 1
    This is a bit confusing, since you are interchanging `Array` with `Object`. In JavaScript, there is nothing like an associative array. Those are objects. Can you clearify this? – jwueller Oct 18 '10 at 10:47
  • var dP = $('#calendar').GetDates(); --- dP will now be an array of objects named "October 18 2010 00:00" that contains lists of days of the week, the months of the year and whatnot, which I don't need. I need the name as a string. – Mantar Oct 18 '10 at 10:51
  • Make sure to check `.hasOwnProperty()` in the loop! You will get in serious trouble otherwise. – jwueller Oct 18 '10 at 11:03
  • Oh, right! Thanks for the reminder! <3 – Mantar Oct 18 '10 at 11:50

1 Answers1

0

As elusive stated in comments, you're not dealing with an Array but with an Object.

However, the construct you're probably looking for is the for..in statement that lets you loop through the object's properties.

Something along these lines:

var object1 = { '2010-10-18': 'today', '2010-10-19': 'tomorrow' },
    dateArray = [],
    dateStr = '';

for (dateStr in object1) {
    // here you should probably check that dateStr
    // and the corresponding value are in correct format
    // in case someone or something has extended the Object class
    dateArray.push(dateStr)
}

// dateArray is now [ '2010-10-18', '2010-10-19' ]

Also note that you can't trust that the object's properties will be iterated "in order". See this question.

Community
  • 1
  • 1
kkyy
  • 11,418
  • 3
  • 30
  • 27