Twist
Twist

Reputation: 275

Any modern way to disable sort in Object.assign if objects has numeric keys?

For example: snippet img

var a = {1: '1', 2: '2'}
var b = {3: '3', 4: '4'}

Object.assign({}, a, b)
> {1: "1", 2: "2", 3: "3", 4: "4"}

Object.assign({}, b, a)
> {1: "1", 2: "2", 3: "3", 4: "4"}

Is there way to disable sorting?

Upvotes: 5

Views: 3076

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074535

No, because (as you said) of the numeric keys (or to use the spec's term, integer indexes*).

Object.assign works in the order defined by [[OwnPropertyKeys]], which for ordinary objects is the OrdinaryOwnPropertyKeys abstract operation, which lists the properties in a defined order (integer indexes first, then other string-named properties in order of creation, then Symbol-named properties in order of creation). The resulting object's properties will be enumerated (by operations that follow the defined order) in the same way, and so, integer indexes, numerically, followed by other properties in creationg order.

If your keys weren't integer indexes, you could control the order of the result by pre-creating the properties in the order you wanted them, but not in the case of integer index keys.

So for instance, if your keys were a, b, c, and d, you could determine the order the resulting object's properties were listed (for operations that follow the order):

const x = {a: 'a', b: 'b'};
const y = {c: 'c', d: 'd'};
const result1 = Object.assign({c: null, d: null, a: null, b: null}, x, y);
console.log(JSON.stringify(result1));
const result2 = Object.assign({c: null, d: null, a: null, b: null}, y, x);
console.log(JSON.stringify(result2));
const result3 = Object.assign({a: null, b: null, c: null, d: null}, x, y);
console.log(JSON.stringify(result3));
const result4 = Object.assign({a: null, b: null, c: null, d: null}, y, x);
console.log(JSON.stringify(result4));

Note that I'm using JSON.stringify there for output, because JSON.stringify is defined to follow property order (whereas for-in and Object.keys are not).

But not for your keys, which are integer indexes.

If order is important, usually an object is the wrong data structure; instead, you'd want an array. Arrays are also objects and some of the ordered-ness of an array is just convention (barring optimization), but they have several important order-specific features, not least the length property and their various methods that work in a defined order.


* "integer index" is 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.

Upvotes: 7

Related Questions