0

I have an object like this :

{
    "25276234": {
        "id": "25276234",
        "title": "new",
    },
    "4c57f8b9": {
        "id": "4c57f8b9",
        "title": "aa",
        },
    "c5353527": {
        "id": "c5353527",
        "title": "1",
        },
    "76517feb": {
        "id": "76517feb",
        "title": "bs",
        },
    "b6458d0c": {
        "id": "b6458d0c",
        "title": "new doc",
        },
    "d8ca47f7": {
        "id": "d8ca47f7",
        "title": "AAAA",
        },
    "2a72cba8": {
        "id": "2a72cba8",
        "title": "abcd",
        },
    "73694f31": {
        "id": "73694f31",
        "title": "A",
        }
}

My aim is to sort it based on the title and the final sorted result should be an object of this format only and not an array.

I have tried several ways like -

const sorted = {};
Object
    .keys(data).sort((o1,o2) => {
        return data[o1].title - data[o2].title;
    })
    .forEach((key) => {
        sorted[key] = data[key];
    });

But it is not being sorted for some reason. What am I doing wrong and what is the solution?

VATSAL JAIN
  • 561
  • 3
  • 18
  • 3
    See [Does JavaScript guarantee object property order?](/q/5525795/4642212). Objects are not intended to be used as ordered collections. Consider using [`Map`s](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map) instead. – Sebastian Simon Oct 26 '22 at 05:59
  • Can you change the structure something like this - ```[{id: "87f65ea4", title:"A"},{id: "87f6523f", title:"B"},{id: "6543awe23", title:"C"}]``` ? – Anveeg Sinha Oct 26 '22 at 06:02
  • Cant use map need an object only. Is there any solution? – VATSAL JAIN Oct 26 '22 at 06:02
  • @AnveegSinha No need the same format only since this is being used in react and being passed as props so need the same format only – VATSAL JAIN Oct 26 '22 at 06:03
  • 1
    `data[o1].title - data[o2].title` <- this is how you sort numbers or booleans. For strings, it should be `data[o1].title.localeCompare(data[o2].title)`. (FYI, even then `25276234` will always be enumerated first because it is an integer key) – adiga Oct 26 '22 at 06:43
  • @adiga it looks like `25276234` is an `id` field, not a `title` field. The `id` fields all appear to be hex, so they could be sorted using the first method if the values are converted from hex strings to integers first. – nigh_anxiety Oct 26 '22 at 12:57
  • 2
    @nigh_anxiety `25276234` is one of the keys of the object. Integer key will always be enumerated no matter the order of insertion. So, `sorted` object will always enumerate `25276234` first because it is an integer: https://jsfiddle.net/d4mfkaxq/ – adiga Oct 26 '22 at 13:36

0 Answers0