0

I have a Json Object like this:

"value": {
    "date": {
        "2017-03-10": {
            "0": {
                "buy": 0,
                "sell": 0
            },
            "1": {
                "buy": 0,
                "sell": 0
            },
            "2": {
                "buy": 0,
                "sell": 0
            },
        },
    },}

I have all dates in: Multi_Obj["value"]["date"];

and if i use the command sort:

Multi_Obj["value"]["date"].sort(function(a, b) {
a = new Date(a.dateModified);
b = new Date(b.dateModified);
return a>b ? -1 : a<b ? 1 : 0;});

I have this result:

Uncaught TypeError: Multi_Obj.show_data.sort is not a function.

Please Help Me! :)

Diegs
  • 15
  • 2

2 Answers2

0

You can't sort associated arrays because of how they are built in JavaScript, but you can sort it, if you convert it to a tuple. So, if you used to have:

colorPreference = {"favorate":"blue","hate","red"}

The tuple version would be:

colorPreference = [["favorate","blue"],["hate","red"]]

You still have both the key and the value, but now it's in an array-based format which does enforce order. Associated arrays do not enforce order of it's elements.

So, what does our JavaScript look like then:

function toTuples(assocArray) {
    var tuples = [];
    for (var key in assocArray) tuples.push([key, assocArray[key]]);
    return tuples;
}

console.log(toTuples(Multi_Obj["value"]["date"]).sort(function(a, b) {
    a = new Date(a[0]);
    b = new Date(b[0]);
    return a>b ? -1 : a<b ? 1 : 0;
}));

If you're wondering, you can't really convert it back, because then the order would not be preserved. But you can still loop through it:

for (var i = 0, len = output.length; i < len; i++) {
    key = output[i][0];
    value = output[i][1];
}
Neil
  • 13,042
  • 2
  • 26
  • 48
0

You should not rely on a certain order of object properties, even though some newer ES6 methods will guarantee a certain order, but not one you can set arbitrary with a call to sort.

You could instead create an ES6 Map, which acts much like a plain object, but which retains insertion order. This you can use as follows:

const obj = {
    "value": {
        "date": {
            "2017-12-01": "a",
            "2017-03-10": "b",
            "2017-05-20": "c",
            "2016-01-01": "d"
        }
    }
};

// Convert date property to a sorted Map:
obj.value.date = Object.keys(obj.value.date)
    .sort( (a, b) => Date.parse(a) - Date.parse(b) )
    .reduce( (mp, a) => mp.set(a, obj.value.date[a]), new Map );

// Display results (sorted):
obj.value.date.forEach( (value, date) => console.log(date, value) );

Note that the syntax to use with a Map is a bit different. To get one particular entry, you would use the get method:

obj.value.date.get('2017-03-10')
Community
  • 1
  • 1
trincot
  • 211,288
  • 25
  • 175
  • 211