mal200
mal200

Reputation: 389

Order Objects in JavaScript

Let's just say we have 2 JavaScript Objects likes this:

object1 = {
  test: {},
  test2: {},
  users: {},
  colors: {},
  dates:{}
}

object2 = {
  test2: {},
  dates:{},
  test: {},
  colors: {},
  users: {}
}

How can you take the order of object1 to object2 ?

Upvotes: 0

Views: 612

Answers (4)

pe.kne
pe.kne

Reputation: 684

According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#description:

The traversal order, as of modern ECMAScript specification, is well-defined and consistent across implementations. Within each component of the prototype chain, all non-negative integer keys (those that can be array indices) will be traversed first in ascending order by value, then other string keys in ascending chronological order of property creation.

Or this easier to understand resource: https://javascript.info/object#ordered-like-an-object

So I believe you could do the following:

object1 = {
  test: {},
  test2: {},
  users: {},
  colors: {},
  dates:{}
};

object2 = {
  test2: {},
  dates:{},
  test: {},
  colors: {},
  users: {}
};

orderedObject2 = {};
for (let prop in object1){
  orderedObject2[prop] = object2[prop];
}

object2 = orderedObject2;
// now all the matching properties of object2 are in same order as in object1

Upvotes: 0

Chris Wininger
Chris Wininger

Reputation: 691

Hmm, mostly a basic sorting problem with a JavaScript specific twist as this would not be possible in many languages. I am sure this is not the most efficient implementation, but the below should accomplish the job assuming the two objects share the same properites

var i = 0;
for(var arg in object1) {
    if (object2[arg]) {
        var temp = object2[arg];
        delete object2[arg];
        object2[arg] = temp;
    }
}   

Upvotes: 1

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57650

JavaScript object has no concept of order. Order is only applicable to Arrays. Besides no one accesses JavaScript object with numerical indexes. You access it by name of the property. And you already know that name.

The two objects in your question has same properties. As the values are empty both objects are actually same.

Upvotes: 1

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

You can't do it, objects are unordered by definition.
If you want it use an array.

Upvotes: 0

Related Questions