Sort JavaScript objects by key

Source: Internet
Author: User

Problem description

I need to sort the JavaScript objects by key.

So the following:

‘b‘ : ‘asdsad‘, ‘c‘ : ‘masdas‘, ‘a‘ : ‘dsfdsfsdf‘ }

will become:

‘a‘ : ‘dsfdsfsdf‘, ‘b‘ : ‘asdsad‘, ‘c‘ : ‘masdas‘ }

The best solution

method One if you want to iterate over the properties of an object, you can sort the keys and then retrieve the associated values:

var myObj = {
' B ': ' ASDSADFD ',
' C ': ' Masdasaf ',
' A ': ' Dsfdsfsdf '
},
Keys = [],
K, I, Len;
var newobj={};

For (k in myObj) {
if (Myobj.hasownproperty (k)) {
Keys.push (k);
}
}

Keys.sort ();

len = keys.length;

for (i = 0; i < len; i++) {
k = Keys[i];
NEWOBJ[K]=MYOBJ[K];
}

console.log( myObj );console.log(newObj);

 

Alternative implementations used by method two Object.keys :

var myObj = {    ‘b‘: ‘asdsadfd‘,    ‘c‘: ‘masdasaf‘, ‘a‘: ‘dsfdsfsdf‘ }, keys = Object.keys(myObj), i, len = keys.length;keys.sort();for (i = 0; i < len; i++) { k = keys[i]; newObj[k]=myObj[k];}
console.log(keys);
console.log( myObj );
console.log(newObj);

Sort JavaScript objects by key

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.