Skip navigation

So I was fortunate enough to recently have to store data that was stored as two merged Javascript Objects yeasterday. Yeah, I know what your thing ‘everything is an object’. It wasn’t stored as an array, just as a default Object. I wanted my change to be as stealth as possible and not interfere too much with the existing structure of the code base. And I wanted to return a sorted object.

I think I didn’t have JQuery linked in the file and didn’t want to add it unless I had to. I forget things. Anyway, Here’s the code I ended up using (and later scrapping because I decided to just do it in PHP and change some other things)

//first I had to merge my two objects
var myObj1 = somefucntionthatshouldhavebeenreturnarraysbutreturnsanobject();
var myObj2 = someotherfucntionthatshouldhavebeenreturnarraysbutreturnsanobject();
for(var attrname in myObj2) {
if(typeof availableBundles[attrname] === 'undefined') {
myObj1[attrname] = myObj2[attrname];
//so now we have both objects merged into myObj1

//sort myObj1 into a temporary variable called sortedObj
var sortedArr = [];
for (var attrname in myObj1) {
sortedArr.push({key:attrname, value:myObj1[attrname]});
//now we have a sorted array

//now we will parse the sorted array, and put it back into the object
myObj = {};

//in my case I was sorting by the value, not the key, and the value was text, hence the use of localeCompare
sortedArr.sort(function(a, b) {return a.value.localeCompare(b.value);});
for (var i=0;i

So, some interesting things to note here, is that in order to sort by value and not run into duplicate keys overwriting data, we store the value and key as objects, and in order to use the sort() method, we store store them in an array, and then pass into sort() a function that compares the values.
As mentioned in the source code, we use localeComapre to compare two strings. Since this is a sorting method you want to return a negative number os the first value is less than the second, a zero is they are equal, and a postive number is the forst value is greateer than the second. Sort() takes care of the rest.
LocaleCompare is used for strings because that's basically what the function does, it compares two strings and returns an integer based on the above rules. We just need to tell it that we want to compare using sortedArr->value, not sortedArr->key.

Leave a Reply

Your email address will not be published. Required fields are marked *