-3

I have the following Javascript object:

let obj = {
    a: 1,
    b: 2,
    d: 4
}
obj["c"] = 3

When I log this, the keys are in the order a, b, d, c. Is there a way to make it so that c is inserted between b and d?

gkeenley
  • 6,088
  • 8
  • 54
  • 129
  • You can't, `obj` is an **object**, not an array. "Sorting an object" is meaningless – Alex Jan 27 '23 at 15:00
  • Objects don't have an inherent order, so no. Maps *do* have an order, but it's based on when they are inserted, so I'd take obj.keys() (an array), sort it (.sort()) then iterate through it and insert into a map. BTW, your title says "array", but you have no arrays. – mykaf Jan 27 '23 at 15:00
  • let obj = {a: 1, b: 2, d: 4}; let newObj = {}; /* insert whatever */ /* sort after keys and save into newObj */ Object.keys(obj).sort().map(e => {newObj[e] = obj[e];}); /* check newObj */ newObj; – Dxg125 Jan 27 '23 at 15:04

1 Answers1

1

One method is to create a new object with Object.fromEntries after sorting the entries of the original object.

let obj = {
    a: 1,
    b: 2,
    d: 4
}
obj["c"] = 3;
let newObj = Object.fromEntries(Object.entries(obj).sort());
console.log(newObj);

Alternatively, just sort the keys before looping over them.

let obj = {
    a: 1,
    b: 2,
    d: 4
}
obj["c"] = 3;
for (const key of Object.keys(obj).sort()) {
  console.log(key, '=', obj[key]);
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Objects don't have an order, so even creating a new object doesn't guarantee the same order. – mykaf Jan 27 '23 at 15:01
  • 1
    @mykaf No, they do follow insertion order for non-numeric keys. See [here](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order). – Unmitigated Jan 27 '23 at 15:02