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?
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?
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]);
}