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 ?
-
Explain what you have tried.Aravindhan– Aravindhan01/12/2013 03:52:01Commented Jan 12, 2013 at 3:52
4 Answers 4
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.
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;
}
}
-
I guess I do have to agree with the statements above though, this does seem kind of pointless, but I will not that you step through the properties of object2 using a for in loop both before and after running this, they will print in a different order. I understand that the underlying object is implemented in non-ordered way; so doing this won't impact performance, but if you wanted for whatever reason to print the properties of an object in some way this might be useful.Chris Wininger– Chris Wininger01/12/2013 04:18:48Commented Jan 12, 2013 at 4:18
You can't do it, objects are unordered by definition.
If you want it use an array.
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