user3162206
user3162206

Reputation:

Can i use date object as key in JSON object javascript?

I recieved strings of dates in my Javascript as keys of JSON object. I want to replace the keys with their Date objects. So i did this.(postdata is the name of JSON object)

    for (var key in postdata){
        var temp = postdata[key];
        postdata[parseDate(key)] = temp;
        delete postdata[key];           
    }

This is the parseDate function..

    function parseDate(input) {
        var parts = input.split('-');
        return new Date(parts[0], parts[1]-1, parts[2]);
    }

But when i retrieved the keys later and try to sort the keys its not working.

    var date_sort_asc = function (date1, date2) {
         if (date1 > date2) return 1
        if (date1 < date2) return -1
        return 0
    };
    for (var key in postdata){
        graph_label.push(key)
    }
    graph_label.sort(date_sort_asc)

I tried this on list of dates and it worked perfectly. But when retrieved from JSON as keys its not working?

Upvotes: 2

Views: 5026

Answers (2)

Dmytro Yarmak
Dmytro Yarmak

Reputation: 1018

In JavaScript keys of object always convert to strings so it is not good practice to store Date as key of object. I think it is better to create array of objects.

Here is code: http://jsbin.com/tijamepu/1/edit?js,console,output

Upvotes: 1

Quentin
Quentin

Reputation: 943100

You can use strings as property names.

If you try to use a Date object, .toString() will be called on it automatically giving you a property name such as "Tue Apr 01 2014 07:27:26 GMT+0100 (BST)".

Upvotes: 0

Related Questions