0

I've tried to use a function like this - to reorder the object I get back from a call

function sortObject(obj) {
  return Object.keys(obj)
    .sort().reduce((a, v) => {
    a[v] = obj[v];
    return a; }, {});
}

So the object would look like this initially

let myObject = {
    "hero": {
        "body": "dummy text",
        "orderId": 2
    },
    "banner": {
        "body": "dummy text",
        "orderId": 1
    },
    "team": {
        "body": "dummy text",
        "orderId": 0
    }
};

let sortedMyObject = sortObject(myObject);

so I would want to return the object to be in orderId:

{
    "team": {
        "body": "dummy text",
        "orderId": 0
    },
    "banner": {
        "body": "dummy text",
        "orderId": 1
    },
    "hero": {
        "body": "dummy text",
        "orderId": 2
    }
}
The Old County
  • 89
  • 13
  • 59
  • 129
  • Which browser are you using? – evolutionxbox Jun 16 '21 at 09:59
  • 6
    JavaScript objects are not intended to store properties in a certain order, even though there are some rules for it. It is better practice to use an array when order is important. – trincot Jun 16 '21 at 10:01
  • Relevant: [Does ES6 introduce a well-defined order of enumeration for object properties?](https://stackoverflow.com/q/30076219) However, @trincot is correct. You should avoid relying on the order of keys in an object. That can be disturbed without even realising. You should use a different data structure that preserves the order. Perhaps an array or a map. – VLAZ Jun 16 '21 at 10:05
  • well - that's why I got an orderId flag here -- so the data has come back in a possible different order - now I want to order the stack – The Old County Jun 16 '21 at 10:05
  • Yes, but that doesn't address the issue here: your "stack" is not a stack. In JavaScript you should implement this as an array, where the order is determined by the array index. – trincot Jun 16 '21 at 10:10
  • I already mentioned this in the comments in [your other question](https://stackoverflow.com/questions/67996324): You need to pass the sorted entries from that question into `Object.fromEntries()`. Or you can use `reduce` as mentioned in the duplicates – adiga Jun 16 '21 at 10:16
  • I managed to get it working by using the sorted array - and just picking out the block from that – The Old County Jun 16 '21 at 10:20
  • Here's a fiddle using both `fromEntries` and `reduce`: https://jsfiddle.net/m0x9yn42/ – adiga Jun 16 '21 at 10:23

0 Answers0