You cannot create an object whose properties will be enumerated in the order you've said you want with those property keys. As of ES2015, object properties do have an order (officially specified only for some operations, but all modern JavaScript engines also apply it to the unspecified operations). One aspect of that order is that properties whose names are integer indexes as defined by the spec* are visited in numeric order. Your 1
, 2
, 3
, etc. properties fit the definition of integer index keys, and so the combined object's properties will be enumerated in 1, 2, 3, ... order.
Instead, use an array:
const obj3 = [];
Object.keys(obj1).forEach(key => { obj3.push({key, value: obj1[key]}); });
Object.keys(obj2).forEach(key => { obj3.push({key, value: obj2[key]}); });
var obj1 = {
1: "Available",
3: "Available - Sleeps"
};
var obj2 = {
2: "Not Available",
4: "Holidays",
6: "Sick"
};
const obj3 = [];
Object.keys(obj1).forEach(key => { obj3.push({key, value: obj1[key]}); });
Object.keys(obj2).forEach(key => { obj3.push({key, value: obj2[key]}); });
console.log(obj3);
.as-console-wrapper {
max-height: 100% !important;
}
...although technically, if you made those names not integer indexes, you could create an object with properties that would be numerated in that order:
var obj3 = {};
Object.keys(obj1).forEach(key => { obj3["x" + key] = obj1[key]; });
Object.keys(obj2).forEach(key => { obj3["x" + key] = obj2[key]; });
var obj1 = {
1: "Available",
3: "Available - Sleeps"
};
var obj2 = {
2: "Not Available",
4: "Holidays",
6: "Sick"
};
var obj3 = {};
Object.keys(obj1).forEach(key => { obj3["x" + key] = obj1[key]; });
Object.keys(obj2).forEach(key => { obj3["x" + key] = obj2[key]; });
console.log(obj3);
But I don't recommend it.
* Defined here:
An integer index is a String-valued property key that is a canonical numeric String (see 7.1.16) and whose numeric value is either +0 or a positive integer ≤ 253-1.