简体   繁体   中英

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?

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

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)" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM