Q: How to sort nested Firebase DB's nested object array I have a JSON file like this:
const presets = {
  key1: {
    val1: "asd",
    val2: "dsadd",
    singles: {
      likeCount: 23,
    },
  },
  key2: {
    val1: "asd2",
    val2: "dsadd2",
    singles: {
      likeCount: 100,
    },
  },
  key3: {
    val1: "asd3",
    val2: "dasad3",
    singles: {
      likeCount: 15,
    },
  },
  key4: {
    val1: "asd3",
    val2: "dasad3",
    singles: {
      likeCount: 80,
    },
  },
}

And I want to order this file by the likeCount property
Here's what I tried:
Object.keys(presets)
  .map((key) => Object.assign({ key }, presets[key]))
  .sort((a, b) => b.singles.likeCount - a.singles.likeCount)
  .every((preset, index) => {
    fs.appendFile("./data.json", JSON.stringify(preset), () => {})
    return index < 20
  })

and the output:
[
  {
    "key": "key2",
    "val1": "asd2",
    "val2": "dsadd2",
    "singles": {
      "likeCount": 100
    }
  },
  {
    "key": "key4",
    "val1": "asd3",
    "val2": "dasad3",
    "singles": {
      "likeCount": 80
    }
  },
  {
    "key": "key1",
    "val1": "asd",
    "val2": "dsadd",
    "singles": {
      "likeCount": 23
    }
  },
  {
    "key": "key3",
    "val1": "asd3",
    "val2": "dasad3",
    "singles": {
      "likeCount": 15
    }
  }
]

The expected output:
{
  "key2": {
    "val1": "asd2",
    "val2": "dsadd2",
    "singles": {
      "likeCount": 100
    }
  },
  "key4": {
    "val1": "asd3",
    "val2": "dasad3",
    "singles": {
      "likeCount": 80
    }
  },
  "key1": {
    "val1": "asd",
    "val2": "dsadd",
    "singles": {
      "likeCount": 23
    }
  },
  "key3": {
    "val1": "asd3",
    "val2": "dasad3",
    "singles": {
      "likeCount": 15
    }
  }
}

My file's size is 80MB and after I sorted the data, file new file's size becomes 50MB. I mean, some of the data is also missing after the sorting.
My question: How can I sort an object like that without losing or changing anything on the data?

A: You can sort Object.entries and convert it back to an object with Object.fromEntries as long as none of the keys are numeric, in which case they will be iterated over in insertion order.


const presets = {
  key1: {
    val1: "asd",
    val2: "dsadd",
    singles: {
      likeCount: 23,
    },
  },
  key2: {
    val1: "asd2",
    val2: "dsadd2",
    singles: {
      likeCount: 100,
    },
  },
  key3: {
    val1: "asd3",
    val2: "dasad3",
    singles: {
      likeCount: 15,
    },
  },
  key4: {
    val1: "asd3",
    val2: "dasad3",
    singles: {
      likeCount: 80,
    },
  },
}
const res = Object.fromEntries(
     Object.entries(presets)
       .sort(([k1,v1],[k2,v2])=>v2.singles.likeCount - v1.singles.likeCount));
console.log(res);


